【发布时间】:2021-07-26 05:12:22
【问题描述】:
我在这里和编码世界都比较陌生。我目前正在学习 Shell Scripting 课程,但我有点卡住了。
我正在尝试做一些额外的功劳并让脚本检查命令行参数,如果没有给出或只给出 1,则提示用户输入缺失的值。
在大多数情况下,除了数字检查部分之外,我已经能够使其大部分工作。我不完全确定我是否正确地执行了嵌套 if 语句,因为它同时显示了“if”回声和“else”回声。
到目前为止我的脚本:
q=y
# Begins loop
until [[ $q == n ]];do
# Checks command line arguments
if [[ $# -lt 2 ]];then
# Asks for second number if only 1 argument.
if [[ $# == 1 ]];then
read -r -p "Please enter your second number: " y
if [[ y =~ [1-9] ]];then
echo "You've chosen $1 as your first number and $y as your second number."
break
else
echo "This is not a valid value, please try again."
fi
# Asks for both numbers if no arguments.
else
read -r -p "Please enter your first number: " x
if [[ x =~ [1-9] ]];then
break
else
echo "This is not a valid value, please try again."
fi
read -r -p "Please enter your second number: " y
if [[ y =~ [1-9] ]];then
break
else
echo "This is not a valid value, please try again."
fi
echo "You've chosen $x as your first number and $y as your second number."
fi
# If both command line arguments are provided, echo's arguments, and sets arguments as x and y values.
else
echo "You've chosen $1 as your first number and $2 as your second number."
x=$1
y=$2
fi
read -r -p "Would you like to try again? (n to exit): " q
done
当我运行它时,我得到这个输出:
Please enter your first number: 1
This is not a valid value, please try again.
Please enter your second number: 2
This is not a valid value, please try again.
You've chosen 1 as your first number and 2 as your second number.
Please enter your first number:
并且将继续循环而不会中断。任何帮助/指导将不胜感激,谢谢。
【问题讨论】:
标签: bash shell loops if-statement terminal