• Home
  • Shell
    • Emacs
    • Perl
    • screen
    • sed
  • Ubuntu
    • VNC
  • Web Development
    • Javascript
    • Joomla
    • MySQL
    • osTicket
  • Windows
    • Gimp

BASH> if ARRAY [does not] contains string

Oct26
2010
Written by Scott Rowley

Check if an array contains a given string:

teams=(chiefs broncos chargers raiders)
if [[ ${teams[*]} =~ broncos ]]
then
echo "VICTORY!"
fi

Or, if you don’t want it to contain the string then:

teams=(cardinals 49ers seahawks rams)
if [[ ${teams[*]} =~ broncos ]]
then
echo "This conference sucks"
else
echo "VICTORY!"
fi
Posted in BASH - Tagged array, BASH, contain, string
« Perl> Get IP only from logfiles
» BASH> Get all but the last field

2 Comments

  1. antoine's Gravatar antoine
    January 2, 2013 at 4:56 pm

    WRONG!
    It doesn’t work if you try to check if the array contains “b” (I mean, the result would be yes).

  2. antoine's Gravatar antoine
    January 2, 2013 at 5:06 pm

    The right solution is include boundaries caractères to the regexp : “\b”
    search=\\bbroncos\\b
    if [[ ${teams[*]} =~ $search ]]
    then
    echo “VICTORY!”
    fi

Corrections? Questions? Comments?

Find an error?
Everything work out great for you?
Have some feedback?
Like to see something added to the article?

PLEASE leave us a comment after the article and let us know how we are doing, or if something needs corrected, improved or clarified.

Thank you!
- The Management

Advertisement

Sudo Bash
By Geeks - For Geeks

Back to Top