Bash Script Disk Partition Using Fdisk Command

Bash Script Disk Partition Using Fdisk Command

I have done new partition creation and mount the disk with manual interaction one after another, i got worked for me. But instead of doing manually i am planning to write the bash script to do all the changes for us without manual interaction.

I found the below script from internet, but i am not understand how the default option will behave using below sed command

# to create the partitions programatically (rather than manually)
# we're going to simulate the manual input to fdisk
# The sed script strips off all the comments so that we can 
# document what we're doing in-line with the actual commands
# Note that a blank line (commented as "defualt" will send a empty
# line terminated with a newline to take the fdisk default.
sed -e 's/\s*\([\+0-9a-zA-Z]*\).*/\1/' << EOF | fdisk ${TGTDEV}
  o # clear the in memory partition table
  n # new partition
  p # primary partition
  1 # partition number 1
    # default - start at beginning of disk 
  +100M # 100 MB boot parttion
  n # new partition
  p # primary partition
  2 # partion number 2
    # default, start immediately after preceding partition
    # default, extend partition to end of disk
  a # make a partition bootable
  1 # bootable partition is partition 1 -- /dev/sda1
  p # print the in-memory partition table
  w # write the partition table
  q # and we're done
EOF

sudo fdisk /dev/sdc
p
n
1
p
w
lsblk
sudo mkfs -t ext4 /dev/sdc1

But after entering option p,n,1, i wanna make default for the rest of activity then finally i need write using option w.

Can you please some one help me how to make it work

code for sfdisk

  echo ';' | sfdisk /dev/sdc
  mkfs.ext4 /dev/sdc1
  mount /dev/sdc1 /opt/app/
  uid=`blkid | grep sdc1 | sed -n 's/.*UUID=\"\([^\"]*\)\".*/\1/p'`
  echo "UUID=$uid /opt/app ext4  defaults  0  2" >> /etc/fstab

After executing sfdisk command after rebooting by REHL7 system not coming up back normal mode.

7

1 Answer

You can do this concept via regular fdisk this way:

fdisk /dev/sdb << EOF
p
n
1



p
w
EOF

You merely need to know how many default values are needed. You can have more, without any major consequences (cosmetic ones will occur, however)

n has a max of 4 options [number, first, last, remove_old_fstype]

so you'd add ( 4 - len(args) ) newlines, then proceed.

PS n doesn't need 1 as the default argument ( as 1 is a default argument ), but the method I described above should work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.