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.
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:
#!/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.