Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I'm trying to see if first argument exists in an array:

#!/bin/bash

action="$1"
actions=( install run )
actionOK=false

for i in "${actions[@]}"
do
    if [ $i=$action ]; then
        actionOK=true
    fi
done

echo $actionOK

if [ $actionOK = false ]; then
    echo "unknown action: $action"
fi

now when trying wan27 run, the script echoes true, but it also echoes true for an action that is not in array, such as test, foo, bar or whatever

share|improve this question

2 Answers 2

up vote 2 down vote accepted

I think your script was working for "install", but not "run".

You need to do:

for i in "${actions[@]}"
do
  ...
done

This is because $actions expands to only the first element of the array.

$ array=( a b c )
$ echo $array
a
$ echo "${array[@]}"
a b c

See the bash arrays documentation for more details about how arrays work.

Any element of an array may be referenced using ${name[subscript]}. The braces are required to avoid conflicts with the shell's filename expansion operators. If the subscript is ‘@’ or ‘*’, the word expands to all members of the array name.

share|improve this answer
    
thanks for the update! yet it still outputs true whether the action is in array or not :( –  François Vespa Feb 9 '11 at 10:06
    
Then you've got another bug somewhere else. Is that the whole code or is there more? Are there any errors? Maybe you need to change the first line from #!/bin/sh to #!/bin/bash? –  Mikel Feb 9 '11 at 10:07
    
I'll update my question to post the all code –  François Vespa Feb 9 '11 at 10:08
    
Are you sure that is the script you are running? Are you typing wan27 or ./wan27? What does type wan27 say? –  Mikel Feb 9 '11 at 10:10
3  
Hang on. [ $i=$action ] needs to have spaces like this: [ $i = $action ]. Your original post had spaces. –  Mikel Feb 9 '11 at 10:12

I tried the corrected script by François Vespa and it works for me ok, it outputs "unknown action: ..." if I pass something else than run or install.

The only error I see is when I don't pass any argument. You should check for [ $# -gt 0 ] or [ $# -eq 1 ] to find out if arguments were passed at all.

share|improve this answer
    
The problem was the missing spaces in [ $i=$action ]. Every part between [ and ] needs to be separated by spaces, because [ is a command that takes three arguments when using =. –  Mikel Feb 9 '11 at 10:44

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.