Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash compare a string vs a list of strings

Tags:

regex

bash

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 do I fix is_bad_fruit so that it is true if fname contains one of the bad_fruit strings?

like image 290
kfmfe04 Avatar asked Oct 07 '12 11:10

kfmfe04


People also ask

What is $() in bash?

$() means: "first evaluate this, and then evaluate the rest of the line". Ex : echo $(pwd)/myFile.txt. will be interpreted as echo /my/path/myFile.txt. On the other hand ${} expands a variable.

What is $_ in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.

What is =~?

The =~ operator is a regular expression match operator. This operator is inspired by Perl's use of the same operator for regular expression matching.


2 Answers

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
like image 44
Ansgar Wiechers Avatar answered Sep 20 '22 01:09

Ansgar Wiechers


Try 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 useless use of ls

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

like image 54
Gilles Quenot Avatar answered Sep 18 '22 01:09

Gilles Quenot