I'm trying to create an if else statement to verify that the user has entered something. If they have it should run through the commands, and if not i want to echo a help statement.

  • With read, typically the user has to hit Enter before the script progresses; you can then test the input... – jasonwryan Dec 22 '14 at 21:29

An example (fairly easy) is as following. A file named userinput is created which contains the following code.


# create a variable to hold the input
read -p "Please enter something: " userInput

# Check if string is empty using -z. For more 'help test'    
if [[ -z "$userInput" ]]; then
   printf '%s\n' "No input entered"
   exit 1
   # If userInput is not empty show what the user typed in and run ls -l
   printf "You entered %s " "$userInput"
   ls -l

To start learning bash, I recommend you to check the following link http://mywiki.wooledge.org/

| improve this answer | |

If you want to know if the user entered a specific string, this could help:


while [[ $string != 'string' ]] || [[ $string == '' ]] # While string is different or empty...
    read -p "Enter string: " string # Ask the user to enter a string
    echo "Enter a valid string" # Ask the user to enter a valid string
    command 1 # If the string is the correct one, execute the commands
    command 2
    command 3
| improve this answer | |

When multiple choices are valid, make a while condition to match regular expression:

For example:


while ! [[ "$image" =~ ^(rhel74|rhel75|cirros35)$ ]] 
  echo "Which image do you want to use: rhel74 / rhel75 / cirros35 ?"
  read -r image

It will keep asking for input, until entering one of the three choices.

| improve this answer | |
  • It would be better to use a select statement in bash, if the issue was to restrict the choice to a set of options. – Kusalananda Apr 5 '19 at 10:03
  • @Kusalananda, rather than giving -1, give an actual example! My suggestion works good. Show that your suggestion is good too. Don't just give -1 because you can - it's really not helpful for other readers. – Noam Manos Apr 15 '19 at 11:19
  • Here's an example: select image in rhel74 rhel75 cirros35; do [ -n "$image" ] && break; done – Kusalananda Apr 15 '19 at 12:02
  • @Kusalananda now this is very helpful, thanks! I would have also add [ -z "$image" ] && select ... to skip the whole selection, if $image is already set. – Noam Manos Apr 15 '19 at 14:44

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.