I have an .img file from which I would like to extract 2 values derived with fdisk, as strings in 2 variables.
fdisk -l /home/documents/image-of-sd-card.img
Disk /home/documents/image-of-sd-card.img: 14,84 GiB, 15931539456 bytes, 31116288 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xc680d152
Device Boot Start End Sectors Size Id Type
/home/documents/image-of-sd-card.img1 8192 655359 647168 316M c W95 FAT32 (LBA)
/home/documents/image-of-sd-card.img2 655360 31115263 30459904 14,5G 83 Linux
The values I would need are the last unit from "Sector size" (512) and the End size of the second partition (31115263). How to achieve that? I would prefer a Bash based solution so that I could integrate this into an existing Shell script.
As an absolute beginner in Linux I just played around with some greb commands but to no avail.
Here a steps by step explanation to help you in your bash learning
raw_content=$(fdisk -l /home/documents/image-of-sd-card.img)
sector_size=
second_partition_size=
while read i
do
if [[ "$i" == "Sector size"* ]]; then
echo ">>>>$i"
echo "$i" | cut -d ' ' -f 7
sector_size=$(echo "$i" | cut -d ' ' -f 7)
elif [[ "$i" == "/home/documents/image-of-sd-card.img2"* ]]; then
echo ">>>>$i"
echo "$i" | awk -F' ' '{ print $3 }'
second_partition_size=$(echo "$i" | awk -F' ' '{ print $3 }')
fi
done <<< "$raw_content"
echo -e "\nResults:"
echo "sector_size: $sector_size"
echo "second_partition_size: $second_partition_size"
Output:
raw_content=$(...)
will save all the output in a varwhile read i ... done <<< "$raw_content"
will iterate line by line and set the value in i varif [[ "$i" == "Sector size"* ]];
will ask if string starts with ...echo "$i" | cut -d ' ' -f 7
will split by one space and get you the desired columnecho "$i" | awk -F' ' '{ print $3 }'
will split by several spaces and get you the desired column