OnWorks Linux and Windows Online WorkStations

Logo

Free Hosting Online for WorkStations

< Previous | Contents | Next >

Unanticipated Expansions

It’s possible to have errors that only occur intermittently in a script. Sometimes the script will run fine and other times it will fail because of the results of an expansion. If we re- turn our missing semicolon and change the value of number to an empty variable, we


can demonstrate:



#!/bin/bash


# trouble: script to demonstrate common errors


number=


if [ $number = 1 ]; then

echo "Number is equal to 1." else

echo "Number is not equal to 1."

fi

#!/bin/bash


# trouble: script to demonstrate common errors


number=


if [ $number = 1 ]; then

echo "Number is equal to 1." else

echo "Number is not equal to 1."

fi


Running the script with this change results in the output:



[me@linuxbox ~]$ trouble

/home/me/bin/trouble: line 7: [: =: unary operator expected Number is not equal to 1.

[me@linuxbox ~]$ trouble

/home/me/bin/trouble: line 7: [: =: unary operator expected Number is not equal to 1.


We get this rather cryptic error message, followed by the output of the second echo command. The problem is the expansion of the number variable within the test com- mand. When the command:



[ $number = 1 ]

[ $number = 1 ]


undergoes expansion with number being empty, the result is this:


[ = 1 ]

[ = 1 ]


which is invalid and the error is generated. The = operator is a binary operator (it requires a value on each side), but the first value is missing, so the test command expects a unary operator (such as -z) instead. Further, since the test failed (because of the error), the if command receives a non-zero exit code and acts accordingly, and the second echo command is executed.

This problem can be corrected by adding quotes around the first argument in the test

command:


[ "$number" = 1 ]

[ "$number" = 1 ]


Then when expansion occurs, the result will be this:



[ "" = 1 ]

[ "" = 1 ]


which yields the correct number of arguments. In addition to empty strings, quotes should be used in cases where a value could expand into multi-word strings, as with filenames containing embedded spaces.


Top OS Cloud Computing at OnWorks: