Manth Manth - 5 months ago 18
Bash Question

Shell command to calculate certain % of disk size

I am writing shell script to calculate 15% of total disk size of user's home directory. I have this command which gets me(somewhat) what I want but not sure if there is better way of doing this.

df -hT /home/user1 | grep -vE '^Filesystem' | awk '{ print $2 }'


this command outputs:


<blank line>


516G


how do I extract 516 is my question if this command is right way of doing this.

Answer

Another way to do this in awk without grep:

df -hT /home/user | awk '$1 ~ "sda1"{gsub(/[A-Z]/,"",$4); print $4}'

The test on the front of the awk block $1~"sda1" is just checking to see that your main hard drive is the one that df is looking at. This is a lot safer than grabbing df records that don't contain filesystem which may spit out more than just your main drive if you stick another drive in the box, or mount some NFS drives.

gsub(/[A-Z]/, "", $4) just replaces out any capital letters in $4 (the size of the drive) with nothing "". That should suffice since, I believe, all of the disk size suffixs (K, M, G, etc..) are capital letters. After that's done, we print the new and improved $4.

Comments