thundium
thundium

Reputation: 1063

How to check if certain words is contained by an argument or not

I run my script like

./test.sh -c "red blue yellow"
./test.sh -c "red blue"

And in the bash, the variable "collor" will be assigned by "red blue yellow" or "red blue"

echo $collor
red blue yellow

Two questions:

A: "red" is an important parameter for me, how can I know if red is contained in vairable color ?

if [ red is in color] ; then "my operation"

B: I have a color list with only 3 colors, how can I check if there is non-defined color passed to the script

./test.sh -c "red green yellow"

How can i define the color list and how can I do the check so that I will get the prints

Warnings: wrong color is green is passed to script

Thanks

Upvotes: 3

Views: 146

Answers (2)

thkala
thkala

Reputation: 86333

(A) can be handled somewhat using wildcard string comparison:

if [[ "$color" = *red* ]]; then
    echo 'I am the Red Queen!'
elif [[ "$color" = *white* ]]; then
    echo 'I am the White Queen!'
fi

The problem with this approach is that it does not handle word boundaries very well (or at all); red will trigger the first condition, but so will orange-red and bored. In addition, (B) will be hard (or impossible) to implement in this manner.

The best way to deal with this would be to assign the color list to a Bash array:

COLORS=($color)

for i in "${COLORS[@]}"; do
    if [[ "$i" = "red" ]]; then
        echo 'I am the Red Queen!'
    elif [[ "$i" = "white" ]]; then
        echo 'I am the White Queen!'
    fi
done

You can then use a nested loop to iterate over another array that contains the allowed colors and report any input color that is not found there.

Upvotes: 1

devnull
devnull

Reputation: 123478

A: "red" is an important parameter for me, how can I know if red is contained in vairable color?

You could say:

if [[ "$2" == *red* ]]; then
  echo "Color red is present ..."
fi

The condition would be true only if the color red was included in the arguments to the script (./test.sh -c "red blue yellow").

B: I have a color list with only 3 colors, how can I check if there is non-defined color passed to the script

colors=(red blue yellow)       # color list with three colors
IFS=$' ' read -a foo <<< "$2"
echo "${#foo[@]}"
for color in "${foo[@]}"; do
  if [[ "${colors[@]}" != *${color}* ]]; then
    echo incorrect color $color
  fi
done

Upvotes: 0

Related Questions