The -z
operator is true if its argument is an empty string. hello
is not an empty string, so the else
clause is taken.
Probably you meant to say simply
if [[ "$1" ]]; then
echo "$1"
else
echo 'no variable'
fi
Notice also when to wrap quotes around a shell variable (basically always, at least until you understand when you might not want to) and the preference for [[
over [
in Bash scripts.
But probably more idiomatically, just check if $#
is equal to 1
, or larger than zero if you want to allow multiple arguments. This will work the same regardless of whether some of those arguments are empty strings.
For completeness, the way to get your original script to take the if
branch would be
./bash_script.sh ''
(or alternatively with double quotes instead of single around the empty argument).