Read Command : How to verify user has typed something

61,212

Solution 1

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/

Solution 2

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
    ...
    ...

Solution 3

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.

Share:
61,212

Related videos on Youtube

HS'
Author by

HS'

Updated on September 18, 2022

Comments

  • HS'
    HS' over 1 year

    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.

    • Admin
      Admin over 9 years
      With read, typically the user has to hit Enter before the script progresses; you can then test the input...
  • Kusalananda
    Kusalananda about 5 years
    It would be better to use a select statement in bash, if the issue was to restrict the choice to a set of options.
  • Noam Manos
    Noam Manos about 5 years
    @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.
  • Kusalananda
    Kusalananda about 5 years
    Here's an example: select image in rhel74 rhel75 cirros35; do [ -n "$image" ] && break; done
  • Noam Manos
    Noam Manos about 5 years
    @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.