0

I need to check user input of 5 characters against a predetermined list of servers in an if then statement to ensure the then statement only acts upon a correct input.

Here is my code

    printf "please select a system (serv1, serv2, serv3 or serv4):"
    read -e -n 5 input
      if [[ $input == "serv1" || "serv2" || "serv3" || "serv4" ]]
        then
          execute some code with $input value
        else
          echo "$input is an invalid selection"
      fi

This issue I'm having is regardless of user input it acts as if it's a valid entry.

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
pretz
  • 232
  • 2
  • 14
  • I think this question may provide some insight: https://stackoverflow.com/questions/21157435/how-can-i-compare-a-string-to-multiple-correct-values-in-bash – j_b Mar 29 '22 at 14:49

3 Answers3

2

The conditional requires repetition of the $input variable like so:

if [[ $input == "serv1" || $input == "serv2" || $input == "serv3" || $input == "serv4" ]]
  then
      execute some code with $input value
    else
      echo "$input is an invalid selection"
  fi    
Zlemini
  • 4,827
  • 2
  • 21
  • 23
1

As @Zlemini already stated, you need to fix the syntax of your if statement, because a string without a comparison/operator will always return to true.

What you could alternatively do is the following:

VALID_SERVERS="serv1 serv2 serv3 serv4"

if [[ "${VALID_SERVERS}" == *"$input"* ]]; then
  echo "execute some code with $input value"
else
  echo "$input is an invalid selection"
fi  

The code above will check whether or not the provided value is a substring of VALID_SERVERS.

VeryDogeWow
  • 142
  • 7
1

Another way of doing this is to use a case statement:

#!/bin/bash

printf "please select a system (serv1, serv2, serv3 or serv4): "
read -e -n 5 input

case $input in
    serv1 | serv2 | serv3 | serv4) echo "execute some code with $input value";;
                                *) echo "$input is an invalid selection";;
esac
fpmurphy
  • 2,464
  • 1
  • 18
  • 22