Why am I getting a 'unary operator expected' error?
[ "$THEME" ]
will evaluate to false if $THEME
is undefined or an empty string and true otherwise. See http://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html#Bash-Conditional-Expressions. You can rearrange your if statement to exploit this behavior and have an even simpler conditional:
if [ "$THEME" ]; then cd 'workspace/aws/ghost/'$THEME'/' grunt watch else echo 'Need to specify theme from the following' ls workspace/aws/ghost fi
"$THEME"
needs to be in double-quotes, in case its value contains whitespace.
You need quotes around $THEME
here:
if [ $THEME == '' ]
Otherwise, when you don't specify a theme, $THEME
expands to nothing, and the shell sees this syntax error:
if [ == '' ]
With quotes added, like so:
if [ "$THEME" == '' ]
the expansion of an empty $THEME
yields this valid comparison instead:
if [ "" == '' ]
This capacity for runtime syntax errors can be surprising to those whose background is in more traditional programming languages, but command shells (at least those in the Bourne tradition) parse code somewhat differently. In many contexts, shell parameters behave more like macros than variables; this behavior provides flexibility, but also creates traps for the unwary.
Since you tagged this question bash, it's worth noting that there is no word-splitting performed on the result of parameter expansion inside the "new" test syntax available in bash (and ksh/zsh), namely [[
...]]
. So you can also do this:
if [[ $THEME == '' ]]
The places you can get away without quotes are listed here. But it's a fine habit to always quote parameter expansions anyway except when you explicitly want word-splitting (and even then, look to see if arrays will solve your problem instead).
It would be more idiomatic to use the -z
test operator instead of equality with the empty string:
if [ -z "$THEME" ]
You technically don't need the quotation marks in this simple case; [ -z ]
evaluates to true. But if you have a more complicated expression, the parser will get confused, so it's better to just always use the quotes. Of course, [[
...]]
doesn't require any here, either:
if [[ -z $THEME ]]
But [[
...]]
is not part of the POSIX standard; for that matter, neither is ==
. So if you care about strict compatibility with other POSIX shells, stick to the quoting solution and use either -z
or a single =
.