Home > Enterprise >  How to check read input for validity in bash script
How to check read input for validity in bash script

Time:03-30

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.

CodePudding user response:

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    

CodePudding user response:

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.

CodePudding user response:

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
  •  Tags:  
  • bash
  • Related