2

The simplest script:

#!/bin/bash

myarray=("abc" "bcd" "cde")
 
if ${myaaray[0]} = "abc" ;
then
 echo "abc"
fi

I receive:

./a.sh: line 5: =: command not found

1 Answer 1

5

That's a typo. ${myaaray[0]} should be ${myarray[0]}. It's expanded as empty and then reads as

if = "abc"

to the shell, hence the error since there is no command named =. Also, the semicolon is a useless null statement and can be removed. You only need it if you place the then on the same line:

if command; then
   do_something
fi

Anyway, you also need to tell the shell you want a string comparison, usually with the test utility.

if test "${myarray[0]}" = "abc"; then
    echo "abc"
fi

If you need to perform a set of tests on strings, maybe the case command is useful:

case "${myarray[0]}" in
(abc)   echo "Start of the alphabet";;
(xyz)   echo "End of the alphabet";;
(*)     echo "Somewhere else";;
esac
Sign up to request clarification or add additional context in comments.

3 Comments

In Bash you would generally prefer [[ over [ aka test
@tripleee I'm in favor of using non-bashisms when they are not needed. But yes, [[ is an alternative avoiding some of the idiosyncrasies of test.
If you are using arrays anyway, trying to comply with POSIX in other parts is just weird. [[ has some clear benefits in error handling and freedom from legacy behaviors from the Bourne shell. But sure, just commenting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.