I need to make a simple bash script showing the percentage that the home directory occupies in all the root folder. It should be like this:
Root filesystem size: 238G
Home directory size: 125G
Home directory uses 52% of /
Here is the code that I have written so far:
#!/bin/bash
r=$(df -hm / | awk '{print $2}' | awk 'END{print}')
h=$(cd ~; du -hs | awk '{print $1}')
echo "Root filesystem size: $r"
echo "Home diectory size: $h"
#???
echo "Home directory uses ??? of /"
I'm not sure how can I do the division. I think that I should make this work with the bc
command. Any help?
CodePudding user response:
The dirty hack would be to do just awk
and let it all do the conversions:
echo "...$(awk '{printf "%.0f", $1/$2}' <<<"$r $h")% ..."
The proper script would remove -h
and work on bytes. Convert to human-readable with numfmt
. Do the calculation with bash $((...))
arithmetic expansion.
CodePudding user response:
First get the two sizes in same unit, e.g., 1k blocks, and next pass them to a bc
script. Example with bash, GNU bc 1.07.1, and the df
and du
utilities from GNU coreutils 8.32:
$ declare -a tmp
$ tmp=( $(df -k --output=size /) )
$ r="${tmp[1]}"
$ tmp=( $(du -ks ~) )
$ h="${tmp[0]}"
$ p=$( bc <<< "scale=2; 100*$h/$r" )
$ echo "Root filesystem size: $r K"
Root filesystem size: 492126216 K
$ echo "Home directory size: $h K"
Home directory size: 15284497 K
$ echo "Home directory uses $p% of /"
Home directory uses 3.10% of /
Note: the
scale=2
statement defines the number of digits after the decimal point (2 in this case, adapt to your needs).
CodePudding user response:
I believe you're making a mistake, using du -hs
for one directory and df ...
for the root directory: everything is inside the root directory, but there might be different file systems, which won't be counted while using df ...
, therefore I'd advise you:
dir_usage=$(du -hs .)
cd /
root_usage=$(du -hs .)
echo "Root root size: $root_usage"
echo "Home directory size: $dir_usage"
echo "Percentage: $(($dir_usage * 100 / $root_usage))"
For your information: $((x * 100 / y))
is the way to perform standard UNIX integer arithmetic.