How do i use the if/elif/else conditional statements in bash shell scripts?
-
Also see: How do i use the if/else conditional statements in bash shell scripts?
Here is the structure for if/elif/else conditionals.
if condition; then action elif condition; then action else action fi
Using the same script in How do i use the if/else conditional statements in bash shell scripts? we will expand on it.
Let's add a condition to check if the directory exists. The
! not
in the elif can be within the square bracket or outside.if [ $# -lt 1 ]; then echo "You must specify a directory name" echo "Usage: $0 <directoryname>" exit 1 elif ! [ -d $1 ]; then echo "That directory does not exist" else du -sh $1 fi
Test all conditions.
Run script as normal
$ ./dirsize.sh /home/trainer/bin 26M /home/trainer/bin
Run script with directory that does not exist.
$ ./dirsize.sh /home/trainer/bino That directory does not exist
Run script without a positional parameter.
$ ./dirsize.sh You must specify a directory name Usage: ./dirsize.sh <directoryname>
© Lightnetics 2024