0

Trying to set rules if a certain variable is put into place, can someone identify wtf I'm missing here?

test.sh:

#!/bin/bash
args=($@)
if [ "$@" = "--cron" ]; then 
 echo "WORKS!";
    else echo "FAILS"
fi

output of ./test.sh:

./test.sh: line 3: [: =: unary operator expected
FAILS

However, when I run ./test.sh --cron, it works, and WORKS is output.

user229044
  • 232,980
  • 40
  • 330
  • 338
cbcp
  • 339
  • 2
  • 6
  • 12

3 Answers3

3

The correct way to do this varies a bit depending on exactly what you're trying to do. If you want to check whether the first argument is --cron, use this:

if [ "$1" = "--cron" ]; then

If you want to check whether the only argument is --cron, use this:

if [ "$*" = "--cron" ]; then

(Note that this is one of very few cases where "$*" is the right way to do something -- it expands to all arguments separated by spaces, but treated as a single word for parsing purposes.)

If you want to check whether any argument is --cron, use this:

cronopt=false
for argument; do
    if [ "$argument" = "--cron" ]; then
        cronopt=true
        break    # note: if you are scanning the arguments for other things too, remove this
    fi
done
if $cronopt; then
    ...

BTW, I'm not sure what you're using the args=($@) line for, but if you want to store the arguments in an array the correct way to do it is args=("$@") -- the quotes keep it from doing word splitting, filename expansion, etc before putting the args into the array.

Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
1

This should work, but only for the first element, of you want more you might have to do a for or while loop to iterate thru the arguments.

#!/bin/bash
args=($1)
if [ $args ] && [ $args = "--cron" ]; then
  echo "WORKS!";
    else echo "FAILS"
fi
nooitaf
  • 1,466
  • 11
  • 18
0

In this case, I believe "$@" is too well quoted.

Try comparing against "$1", or use:

#!/bin/bash
args=($@)
if [ "$*" = "--cron" ]; then 
    echo "WORKS!";
else
    echo "FAILS"
fi
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
dstromberg
  • 6,954
  • 1
  • 26
  • 27
  • 1
    @muistooshort: No; there's a huge difference between `"$*"` (a single string) and `"$@"` (as many strings as there are arguments). See also [How to iterate over arguments in bash script](http://stackoverflow.com/questions/255898/how-to-iterate-over-arguments-in-bash-script/256225#256225) and [Bash: being space safe when saving `"$@"` in a variable](http://stackoverflow.com/questions/5851877/bash-being-space-safe-when-saving-in-a-variable/5851983#5851983) – Jonathan Leffler Sep 16 '12 at 03:46
  • @JonathanLeffler: I missed the switch to `$*`. At least I've been reminded why I stopped writing shell scripts in favor Perl scripts. – mu is too short Sep 16 '12 at 04:32