目录
Interactive
Use read
command to to get input from the user.
简单的示例
#!/usr/bin/env bash
read -p "What is your first name: " NAME
# -p: put the prompt on the same line as the user input
echo "Your name is: $NAME"
exit 0
校验用户输入
#!/usr/bin/env bash
VALID=0
while [ $VALID -eq 0 ]
do
read -p "Please enter your name and age: " NAME AGE
if [[ ( -z $NAME ) || ( -z $AGE ) ]]
then
echo "Not enough parameters passed"
continue
elif [[ ! $NAME =~ ^[A-Za-z]+$ ]]
then
echo "Non alpha characters detected [$NAME]"
continue
elif [[ ! $AGE =~ ^[0-9]+$ ]]
then
echo "Non digit characters detected [$AGE]"
continue
fi
VALID=1
done
echo "Name = $NAME, Age = $Age"
exit 0
猜数字游戏
#!/usr/bin/env bash
COMPUTER=$(($RANDOM%100))
WIN=0
while [ $WIN -eq 0 ]
do
# read in the number
read -p "Please enter your number (0-100): " NUMBER
# validation
if [ -z $NUMBER ]
then
echo "Please enter one parameter"
continue
elif [[ ! $NUMBER =~ ^[0-9]+$ ]]
then
echo "Non digit characters detected [$NUMBER]"
continue
elif [ $NUMBER -gt $COMPUTER ]
then
echo "Enter a smaller number"
continue
elif [ $NUMBER -lt $COMPUTER ]
then
echo "Enter a bigger number"
continue
fi
WIN=1
done
echo "That's it! The number is $COMPUTER ."
exit 0
References
LinkedIn Learning: https://www.linkedin.com/learning/learning-linux-shell-scripting-2018