0
#!/bin/bash

declare -a all=("a" "b" "c")

echo -n  "Please enter one value ${all[@]} [ENTER]: "
read site
echo "You entered $site as site"
read -p "Continue? (Y/N): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1


for item in "${all[@]}"; do
echo $item
 if [[ "${site}" == "${all[@]}" ]]; then
  echo "Site Name validated"
 else
  echo "No Match For Site Name" && exit 1
 fi
done

In the input even if type a, b or c. I am not able to validate input against defined array, not meeting if statement Thanks in advance..

0

A simple regex test like

[[ " ${all[@]} " =~ " $site " ]] && echo in || echo out

might be sufficient. You may want to protect against false positives, though.

And, the way you evaluate the confirmation, it will quit the script with an error exit code if you enter y, Y, or yes in any upper / lower case combination.

2

(I’ll assume that you have changed if [[ "${site}" == "${all[@]}" ]] to if [[ "$site" == "$item" ]].)

Just imagine how your loop executes.  Suppose you type b.  The first iteration of the loop sets item equal to a.  You compare b to a.  If they were equal, you would report validation.  But they aren’t equal, so you report failure and exit.

It’s no better it you type a.  On the first iteration of the loop, item is a and you report success and keep on looping.  Then item becomes b, and you go into the else clause, where you report failure and exit.

The problem is that you report failure if the input is different from any of the valid values.  But any input will be different from at least two of the valid values (invalid inputs will be different from all three).  You need to report success if the input is equal to any of the valid values, and failure otherwise.

Exactly how you do this depends on the big picture.  If reading input and validating it is all that you want to do, you need only a small rearrangement of your current code:

for item in "${all[@]}"; do
    echo "$item"
    if [[ "$site" == "$item" ]]; then
        echo "Site Name validated" && exit 0
    fi
done
echo "No Match For Site Name" && exit 1

But if (as is likely) you want the script to go on and do something with valid input, a good way is to use a flag:

valid=
for item in "${all[@]}"; do
    echo "$item"
    if [[ "$site" == "$item" ]]; then
        echo "Site Name validated" && valid=1
    fi
done
if ! [ "$valid" ]
then
    echo "No Match For Site Name" && exit 1
fi
# (script continues with valid input)
               ︙

P.S. You don’t need to say "${site}" in this context; "$site" is fine.

  • putting the test in a function would probably be a good idea too – ilkkachu Sep 27 '18 at 5:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.