Reputation: 983
A rookie here! This is a very simple one. I am trying to write a script that asks for user inputs. Then read the inputs and do some stuff with it. But I first want to make sure inputs are provided.
Example:
echo "Please provide input1:"
read Input1
echo "Please provide input2:"
read Input2
if [ -z "$Input1" ]
echo "You did not provide input1"
exit
else if [ -z "$Input2" ]
echo "You did not provide input2"
exit
fi
However the above doesn't work. Is there a way to make it work while making it look more readable? Is there a better simpler way?
Upvotes: 0
Views: 35
Reputation: 246837
You want elif
not else if
, and you are missing the mandatory then
keywords: https://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs
read -p "Please provide input1: " Input1
read -p "Please provide input2: " Input2
if [ -z "$Input1" ]; then
echo "You did not provide input1"
exit
elif [ -z "$Input2" ]; then
echo "You did not provide input2"
exit
fi
If, instead of exiting, you want to provide a default value, you can do:
read -p "Please provide input1: " Input1
read -p "Please provide input2: " Input2
: ${Input1:=first default value}
: ${Input2:=second default value}
echo "Input1: $Input1"
echo "Input2: $Input2"
Upvotes: 1