I want to check if I do have enough space before executing my script. I thought about
#!/bin/bash
set -e
cd
Home=$(pwd)
reqSpace=100000000
if [ (available Space) < reqSpace ]
echo "not enough Space"
exit 1
fi
do something
The space I want to check via
df | grep $Home
Any suggestions?
Bringing it all together (set -e
and cd
omitted for brevity; Bash-specific syntax - not POSIX-compliant):
#!/bin/bash
# Note: Numbers are 1024-byte units on Linux,
# and 512-byte units on macOS.
reqSpace=100000000
availSpace=$(df "$HOME" | awk 'NR==2 { print $4 }')
if (( availSpace < reqSpace )); then
echo "not enough Space" >&2
exit 1
fi
df "$HOME"
outputs stats about disk usage for the $HOME
directory's mount point, and awk 'NR==2 { print $4 }'
extracts the (POSIX-mandated) 4th field from the 2nd output line (the first line is a header line), which contains the available space in 1024-byte units on Linux[1], and 512-byte units on macOS; enclosing the command in $(...)
allows capturing its output and assigning that to variable availSpace
.
Note the use of (( ... ))
, an arithmetic conditional, to perform the comparison, which allows:
referencing variables without their $
prefix, and
use of the customary arithmetic comparison operators, such as <
(whereas you'd have to use -le
if you used [ ... ]
or [[ ... ]]
)
Finally, note the >&2
, which redirects the echo
output to stderr, which is where error messages should be sent.
[1] If you define the POSIXLY_CORRECT
environment variable (with any value), the GNU implementation of df
too uses the POSIX-mandated 512-byte units; e.g., POSIXLY_CORRECT= df "$HOME"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With