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 =
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…