We will see how to create partitions in Linux system (rhel8 in my case) and then increase or decrease the size of that static partition without losing data.
fdisk -l is a command that will list all disks and devices (partitions) present in our system
For creating a static partition I am selecting an available disk /dev/sdb. To enter into this disk use the fdisk command,
- Enter n for creating new partition.
- We can create maximum 4 primary partition, enter p for primary partition (which will be by default).
- give the partition number from 1 to 4.
- Now give the size, I want to create partition of size 5GiB.
- save and exit (wq). Partition will be created.
Now, we have a partition /dev/sdb1 of size 5GiB.
We need to format this created partition, (using ext4 format)
After this finally we have to mount this partition on a directory. I created a new directory for that.
mount /dev/sdb1 /newdir
We can see all the mounted filesystems using df -h command,
I an also adding some file in that directory,
So, now I am unmouting this device (/dev/sdb1) as we can not change the size of a mounted partition
Again enter the disk /dev/sdb and delete the partition which we created (d command) and then again create a new partition (size 8GiB) at the same partition number 1 but don not remove the ext4 signature otherwise we will lose the data as inode table will be cleared for that partition number 1.
Then save and exit (wq).
Use e2fsck command to check the file system for the device (/dev/sdb1) and use resize2fs command to change size of the filesystem according to given size.
e2fsck -f /dev/sdb1
Now, we again mount this device to our directory. And we can see that the size has become 8 GiB. Our data is also there.
Again we need to unmount the device and then we resize the filesystem to reduce the size to 6 GiB (we had 8 GiB)
resize2fs /dev/sdb1 6G
We can again delete and create partition 1 without removing the signatures. If we again use resize2fs it has nothing to do as we have already resized the filesystem to reduce the size.
We have successfully decreased the size of our partition,
So, this is how we can change the size of a static partition in Linux