Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


actions=( install run )

for i in "${actions[@]}"
    if [ $i=$action ]; then

echo $actionOK

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

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
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[@]}"

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

$ array=( a b c )
$ echo $array
$ 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
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


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.