In Bash how do you see if a string is not in an array?

bash, scripting, shell

Solution

You can negate the result of the positive match:

if ! [[ ${accounts[*]} =~ "$account" ]]

or

if [[ ! ${accounts[*]} =~ "$account" ]]

However, notice that if `$account` equals "user", you'll get a match, since it matches a substring of "power_user". It's best to iterate explicitly:

match=0
for acc in "${accounts[@]}"; do
    if [[ $acc = "$account" ]]; then
        match=1
        break
    fi
done
if [[ $match = 0 ]]; then
    echo "No match found"
fi

Problem

I'm trying to do this without adding additional code, such as another for loop. I can create the positive logic of comparing a string to an array. Although I want the negative logic and only print values not in the array, essentially this is to filter out system accounts. My directory has files in it like this: ``` admin.user.xml news-lo.user.xml system.user.xml campus-lo.user.xml welcome-lo.user.xml ``` This is the code I used to do a positive match if that file is in the directory: ``` #!/bin/bash accounts=(guest admin power_user developer analyst system) for file in user/*; do temp=${file%.user.xml} account=${temp#user/} if [[ ${accounts[*]} =~ "$account" ]] then echo "worked $account"; fi done ``` Any help in the right direction would be appreciated, thanks.

Original source