Note that your line
[ "${#}" -eq 1 ] || echo "Invalid number of arguments, expected one."; exit 1
this is the same as
[ "${#}" -eq 1 ] || echo "Invalid number of arguments, expected one."
exit 1
(an unquoted ;
can, in most circumstances, be replaced by a newline character)
This means that the exit 1
statement is always executed regardless of how many arguments were passed to the script. This in turn means that the message The given argument is empty.
would never have a chance of getting printed.
To execute more than a single statement after a test using the "short-circuit syntax", group the statements in { ...; }
. The alternative is to use a proper if
statement (which, IMHO, looks cleaner in a script):
if [ "$#" -ne 1 ]; then
echo 'Invalid number of arguments, expected one.' >&2
exit 1
fi
You have the same issue with your second test.
Regarding
[ -z "" ] && echo A || echo B
This would work for the given example, but the generic
some-test && command1 || command2
would not be the same as
if some-test; then
command1
else
command2
fi
Instead, it is more like
if ! { some-test && command1; }; then
command2
fi
or
if some-test && command1; then
:
else
command2
fi
That is, if either the test or the first command fails, the second command executes, which means it has the potential to execute all three involved statements.
if [ X”” = X”$var” ] ; then echo isempty ; fi
– user2497 Apr 03 '19 at 17:37[ "" = "$var" ]
would work fine; a quoted empty string will not be removed from the argument list of[
. But that's not necessary either, because[ -z "$var" ]
also works just fine. – chepner Apr 03 '19 at 18:50-z
but some version or fork of pdksh gave me errors. Incidentally, it is ~20 years old, thanks for clearing this up. – user2497 Apr 03 '19 at 20:22[ -z "" ]
are not POSIX-compliant. – Charles Duffy Apr 03 '19 at 20:51