Saturday 13 January 2018

bash shell shorthand conditionals

This is a neat way in bash scripts to use conditionals. The basic syntax is
[ condition ] &&/|| action1

counting files in a directory
[ $(ls -1 | wc -l) -ne 1 ] && echo “More than one file in this directory”

checking the number of args passed
[ $# -eq 1 ] || expecting "Expecting one argument"

you can also group multiple actions together as follows
[ $# -eq 1 ] || { echo "Expecting one argument"; exit 1; }

No comments:

Post a Comment