Home > front end >  bash script: how to use array element in if statement
bash script: how to use array element in if statement

Time:12-22

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

CodePudding user response:

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
  •  Tags:  
  • bash
  • Related