2

I ran a script to format a disk with fdisk like this:

(echo n; echo p; echo $number_part; echo $firs_sector; echo $second_sector; echo t; echo $format; echo p; echo w) | fdisk /dev/$disk

when i execute for the first time, the format seen like:

 Device Boot        Start     End      Blocks   Id  System /dev/sdb1 
 2048              2099199     1048576   83          Linux

but in the next execution, the script fail:

command (m for help): Command action
   e   extended
   p   primary partition (1-4)
Partition number (1-4, default 2): Using default value 2
First sector (2099200-20971519, default 2099200): Using default value 2099200
Last sector, +sectors or +size{K,M,G} (2099200-20971519, default 20971519): 
Command (m for help): Partition number (1-4): Value out of range.
Partition number (1-4): Partition number (1-4): Partition number (1-4): 

I wrote a echo to see if the variable number_part contains the right value and if change, but it doesn't change.

I was debug with diferents forms and i seen that if i delete the part: "echo t" of the command, it works.

I don't know why the first time it works but the second it see a error.

BrennQuin
  • 135
  • 6

1 Answers1

3

After creating a partition, you're moving on to setting the partition type: echo t;. Then, to the next prompt, you're outputting the desired partition type number... but that is not what fdisk is asking. It wants to know the number of the partition whose type you wish to set first.

So the sequence should be:

... echo t; echo $number_part; echo $format; ...

Note that when there is only one partition, the partition number question will be omitted because there is only one possible partition to set the type of.

If you want to create partitions in a script, you might consider using sfdisk instead. Its interface is much more suitable for scripting.

telcoM
  • 4,153
  • 12
  • 23