With [[ ... ]]
, you can simply do this (there is no need for double quotes):
[[ $var ]] && echo "var is set"
[[ $var ]] || echo "var is not set or it holds an empty string"
If you really want a function, then we can write one-liners:
is_empty() { ! [[ $1 ]]; } # check if not set or set to empty string
is_not_empty() { [[ $1 ]]; } # check if set to a non-empty string
var="apple"; is_not_empty "$var" && echo "var is not empty" # shows "var is not empty"
var="" ; is_empty "$var" && echo "var is empty" # shows "var is empty"
unset var ; is_empty "$var" && echo "var is empty" # shows "var is empty"
var="apple"; is_empty "$var" || echo "var is not empty" # shows "var is not empty"
Finally, is_unset
and is_set
could be implemented to treat $1
as the name of the variable:
is_unset() { [[ -z "${!1+x}" ]]; } # use indirection to inspect variable passed through $1 is unset
is_set() { ! [[ -z "${!1+x}" ]]; } # check if set, even to an empty string
unset var; is_unset var && echo "var is unset" # shows "var is unset"
var="" ; is_set var && echo "var is set" # shows "var is set"
var="OK" ; is_set var && echo "var is set" # shows "var is set"
Related