Bash compare string with string list

Suppose I have the following code in bash:

#!/bin/bash bad_fruit=( apple banana kiwi ) for fname in `ls` do # want to check if fname contains one of the bad_fruit is_bad_fruit=??? # <------- fix this line if [ is_bad_fruit ] then echo "$fname contains bad fruit in its name" else echo "$fname is ok" fi done 

How to fix is_bad_fruit so that it is true if fname contains one of the bad_fruit strings?

+4
source share
2 answers

Try using the following code:

 #!/bin/bash bad_fruit=( apple banana kiwi ) re="$(printf '%s\n' "${bad_fruit[@]}" | paste -sd '|')" for fname in *; do # want to check if fname contains one of the bad_fruit if [[ $fname =~ $re ]]; then echo "$fname contains bad fruit in its name" else echo "$fname is ok" fi done 

Take care of the useless use of ls

ls is a tool for interactively viewing file information. Its output is formatted for people and will cause errors in scripts. Use globs instead or find. Understand why: http://mywiki.wooledge.org/ParsingLs

+5
source

Another option (using grep with an inner loop and evaluating the exit code):

 #!/bin/bash bad_fruit=( apple banana kiwi ) for fname in *; do for fruit in "${bad_fruit[@]}"; do echo "$fruit" done | grep "$fname" if [ $? -eq 0 ]; then echo "$fname contains bad fruit in its name" else echo "$fname is ok" fi done 
+2
source

Source: https://habr.com/ru/post/1438247/


All Articles