What you are looking for is indirect.
assertNotEmpty() { : "${!1:? "$1 is empty, aborting."}" }
This causes the script to abort with an error message if you execute something like this:
$ foo="" $ assertNotEmpty foo bash: !1: foo is empty, aborting.
If you just want to check if foo empty, instead of interrupting the script, use this instead of the function:
[[ $foo ]]
For example:
until read -p "What is your name? " name && [[ $name ]]; do echo "You didn't enter your name. Please, try again." >&2 done
Also note that there is a very important difference between the empty and unset parameters. You must take care not to confuse these conditions! An empty parameter is one that is installed, but simply set to an empty string. The unset parameter is one that does not exist at all.
In the previous examples, everything is checked for empty parameters. If you want to check the unset parameters and read all the given parameters OK, whether they are empty or not, use this:
[[ ! $foo && ${foo-_} ]]
Use it in a function like this:
assertIsSet() { [[ ! ${!1} && ${!1-_} ]] && { echo "$1 is not set, aborting." >&2 exit 1 } }
Which will only abort the script when the name of the parameter you pass indicates a parameter that is not set:
$ ( foo="blah"; assertIsSet foo; echo "Still running." ) Still running. $ ( foo=""; assertIsSet foo; echo "Still running." ) Still running. $ ( unset foo; assertIsSet foo; echo "Still running." ) foo is not set, aborting.
lhunath May 17 '09 at 12:36 2009-05-17 12:36
source share