目录
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
Shell脚本入门与实践:用户交互和猜数字游戏
这篇博客介绍了Shell脚本的基础知识,包括用户交互、条件判断和循环控制。通过实例展示了如何从用户获取输入,进行参数验证,并实现了一个猜数字游戏,游戏中用户需猜测计算机生成的随机数。文章还提供了LinkedInLearning的进一步学习资源。
2141

被折叠的 条评论
为什么被折叠?



