bashshell

Why am I getting a 'unary operator expected' error?


I'm writing a shell script to streamline my development workflow.

It takes an argument as to which theme folder I'm going to be working in and starts grunt watch on that directory.

If I call the script without the necessary argument I'm currently printing a warning that a theme needs to be specified as a command line argument.

I'd like to print a list of the available options, e.g. theme directories

This is what I have so far...

THEME=$1

if [ $THEME == '' ]
then
    echo 'Need to specify theme'
else
    cd 'workspace/aws/ghost/'$THEME'/'
    grunt watch
fi

Ideally I'd replace the output of the echo line with an ls of the themes parent directory like so

THEME=$1

if [ $THEME == '' ]
then
    echo 'Need to specify theme from the following'
    ls workspace/aws/ghost
else
    cd 'workspace/aws/ghost/'$THEME'/'
    grunt watch
fi

However this gives me the following error

./ghost_dev.sh: line 3: [: ==: unary operator expected

Solution

  • 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 $THEMEyields 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 == '' ]]
    

    See below for a list of places where you can get away without quotes. But it's a fine habit to always quote parameter expansions anyway except when you explicitly want word-splitting (and if you do explicitly want word-splitting, you should re-evaluate the problem you're solving; for example, see if there's a way to solve it with arrays instead).

    It would be more idiomatic to use the -z test operator instead of equality with the empty string:

    if [ -z "$THEME" ]
    

    Of course, [[...]] doesn't require any quotes for this version, 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 =.

    Word-splitting exceptions (copied from http://mywiki.wooledge.org/WordSplitting#Notes):