Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

bash script: how to use array element in if statement

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading