Partitioning by script
A reader requested a demonstration of automatic partitioning.
The task was to create partitions of fixed size and allow the last partition to
consume remaining space. Since the calculations used in this exercise are revelatory
of partitioning issues, the first version of the script is included below, in
the hopes that it might be of use. This section will be expanded in Version 4 of
this HOWTO.
#!/bin/sh
partitionSizes=( 1000000000 256000000 NA ) ; # size in bytes, NA=unspecified
partitionTypes=( 83 82 83 ) ; # see available types: sfdisk -T
partitionFlags=( bootable NA NA )
blockSize=1024
start=1
#---------------------------------------------------------------#
# Do not modify contents below this line
#---------------------------------------------------------------#
function GetGeometry ()
{
numberOfBlocks=`sfdisk -s $1` || exit 1
bytes=$(($numberOfBlocks * 1024))
geometry=(`sfdisk -g $1`) || exit 1
cylinders=${geometry[1]}
heads=${geometry[3]}
sectors=${geometry[5]}
cylinderSize=`echo "scale=4; $numberOfBlocks / $cylinders" | bc` || exit 1
}
function WritePartitionInfo
{
let partitionNumber=$index+1
partitionFlag=${partitionFlags[$index]}
[ $partitionFlag != NA ] || partitionFlag=
partitionType=${partitionTypes[$index]}
[ $partitionType != NA ] || partitionType=
if [ ${partitionSizes[$index]} = "NA" ]
then
cylindersNeeded=
else
cylindersNeeded=`echo "${partitionSizes[$index]} / ( $cylinderSize * $blockSize )" | bc`
fi
echo "${1}$partitionNumber : start= $start, size= $cylindersNeeded, Id= $partitionType, $partitionFlag"
echo "${1}$partitionNumber : start= $start, size= $cylindersNeeded, Id= $partitionType, $partitionFlag" >> $outputFile
[ -z "$start" ] && start=0
[ -z "$cylindersNeeded" ] && cylindersNeeded=0
start=`echo "scale=4; $start + $cylindersNeeded + 1" | bc` || exit 1
}
# ---------------------------------------------------------------------- #
# ------------------------ MAIN ------------------------------ #
# ---------------------------------------------------------------------- #
[ $# -eq 1 ] || { echo "usage: auto_partition.sh device (e.g. /dev/hda)"; exit 1;}
[ -b $1 ] || { echo "$1 not a block device"; exit 1;}
outputFile=${1#/dev/}_proposed
GetGeometry $1
echo "bytes: $bytes"
echo "blocks: $numberOfBlocks"
echo "cylinders: $cylinders"
echo "heads: $heads"
echo "sectors: $sectors"
#echo "unit: cylinders" > $outputFile
> $outputFile
for index in `jot ${#partitionSizes[@]} 0`
do
WritePartitionInfo
done
# This is it! Write the partition table
sfdisk /dev/sda --no-reread < sda_proposed