bash: test if $WORD is in set

  • I am looking for a construct in bash, to decide if a variable $WORD is one of defined words. I need something like this:

    if "$WORD" in dog cat horse ; then 
        echo yes
    else
        echo no
    fi
    

    does bash have such construct? If not, what would be the closest?

  • Joseph R.

    Joseph R. Correct answer

    7 years ago

    This is a Bash-only (>= version 3) solution that uses regular expressions:

    if [[ "$WORD" =~ ^(cat|dog|horse)$ ]]; then
        echo "$WORD is in the list"
    else
        echo "$WORD is not in the list"
    fi
    

    If your word list is long, you can store it in a file (one word per line) and do this:

    if [[ "$WORD" =~ $(echo ^\($(paste -sd'|' /your/file)\)$) ]]; then
        echo "$WORD is in the list"
    else
        echo "$WORD is not in the list"
    fi
    

    One caveat with the file approach:

    • It will break if the file has whitespace. This can be remedied by something like:

      sed 's/[[:blank:]]//g' /your/file | paste -sd '|' /dev/stdin
      

    Thanks to @terdon for reminding me to properly anchor the pattern with ^ and $.

    And `shopt -s nocasematch` might help if you want the search to be case insensitive.

    Note that you have to use ```[[``` and ```]]``` - ```[``` and ```]``` are not enough.

    i was searching for a 'oneliner' to validate my script argument, and this worked perfectly. thank you! `[[ "$ARG" =~ ^(true|false)$ ]] || { echo "Argument received invalid value" ; exit 1 ; }`

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM