ChrizZly
ChrizZly

Reputation: 124

Shell: How to check available space and exit if not enough?

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?

Upvotes: 6

Views: 8938

Answers (2)

mklement0
mklement0

Reputation: 438113

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),[1] which contains the available space in 1024-byte units on Linux[2], 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] Using the GNU implementation of df, which comes with most Linux distros and can be installed on demand on macOS, the extraction command can be simplified to: df "$HOME" --output=avail | tail -1, as David Levy notes

[2] 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".

Upvotes: 14

CMPS
CMPS

Reputation: 7769

Here's one way to do it

df "$Home" | awk 'END{print $4}'

Code:

#!/bin/bash
set -e
cd
Home=$PWD
reqSpace=100000000
SPACE=`df "$Home" | awk 'END{print $4}'`
if [[ $SPACE -le reqSpace ]]
then
    echo "not enough Space"
    exit 1
fi
do something

Upvotes: 1

Related Questions