6

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
8

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

#!/bin/bash

# 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
else
   # If userInput is not empty show what the user typed in and run ls -l
   printf "You entered %s " "$userInput"
   ls -l
fi

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

4

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

#!/bin/bash

while [[ $string != 'string' ]] || [[ $string == '' ]] # While string is different or empty...
do
    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
done 
    command 1 # If the string is the correct one, execute the commands
    command 2
    command 3
    ...
    ...
1

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

For example:

#!/bin/bash

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

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

  • 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 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 at 11:19
  • Here's an example: select image in rhel74 rhel75 cirros35; do [ -n "$image" ] && break; done – Kusalananda Apr 15 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 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.