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.

1

3 Answers 3

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    
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.