KansaiRobot
KansaiRobot

Reputation: 9912

shell scripting, if is executed no matter what

why in this script

#!/bin/sh

if [ $1='all' ];
then
    echo $1
    echo "all"
fi

all is printed no matter what???

For example I do: ./thescript.sh and I got clearly that $1 is empty. But still all is printed. Why? And how can I print "all" when all is passed

Upvotes: 2

Views: 91

Answers (2)

Russ Van Bert
Russ Van Bert

Reputation: 762

Put double-quotes around the variable:

   #!/bin/sh

   if [ "$1" == "all" ];
   then
       echo $1
       echo "all"
   fi 

Upvotes: 1

Robert
Robert

Reputation: 8571

shellcheck has the solution:

SC2077: You need spaces around the comparison operator.

Change to

if [ $1 = 'all' ];

Without the spaces, the thing between the [ and ]is treated as one expression, and man [ says

"STRING equivalent to -n STRING

so any non-empty string is considered true. (i.e., if [ "" ]; would be false.)

That said, you better specify which shell you want in the shebang. On some systems /bin/sh may be bash, on others /bin/dash, or something else. Pick your shell and avoid any problems from bad assumptions on which shell you actually get.

Upvotes: 1

Related Questions