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.
3 Answers
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/
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
...
...
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 inbash
, if the issue was to restrict the choice to a set of options.– Kusalananda ♦Apr 5, 2019 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. Apr 15, 2019 at 11:19
-
Here's an example:
select image in rhel74 rhel75 cirros35; do [ -n "$image" ] && break; done
– Kusalananda ♦Apr 15, 2019 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. Apr 15, 2019 at 14:44
read
, typically the user has to hitEnter
before the script progresses; you can then test the input...