Bash 确认Shell脚本输入
我正在编写一个脚本来执行一个重复的任务,该任务只会更改基本值和位置,例如用户名 我已经编写了提示输入用户名的代码,并验证它是否还没有被使用。我现在试图提示用户脚本接收到的输入是否正确,以及是否不更改它。我的问题是,如果输入正确,它会继续循环。有人有什么建议吗Bash 确认Shell脚本输入,bash,shell,sh,Bash,Shell,Sh,我正在编写一个脚本来执行一个重复的任务,该任务只会更改基本值和位置,例如用户名 我已经编写了提示输入用户名的代码,并验证它是否还没有被使用。我现在试图提示用户脚本接收到的输入是否正确,以及是否不更改它。我的问题是,如果输入正确,它会继续循环。有人有什么建议吗 clear confirm () { # call with a prompt string or use a default echo "CMIT # ${1}" read -r -p "CMIT [Y/n/q]
clear
confirm () {
# call with a prompt string or use a default
echo "CMIT # ${1}"
read -r -p "CMIT [Y/n/q] > " answer
case "${answer}" in
[yY]|[yY][eE][sS]) false ;;
[nN]|[nN][oO]) true ;;
[qQ]|[qQ][uU][iI][tT]) exit 1 ;;
esac
}
while true; do
OE_USER=
while (id -u $OE_USER > /dev/null 2>&1); do
echo "CMIT # What user will this run under?"
read -r -p "CMIT > " OE_USER
if id -u $OE_USER > /dev/null 2>&1; then
echo "CMIT # Bad User Name. Try Again"
fi
done
clear
confirm "Continue installing using '$OE_USER' as the server name?"
done
哇。愚蠢的问题。对不起
clear
GO=true
confirm () {
# call with a prompt string or use a default
echo "CMIT # ${1}"
read -r -p "CMIT [Y/n/q] > " answer
case "${answer}" in
[yY]|[yY][eE][sS]) GO=false ;;
[nN]|[nN][oO]) GO=true ;;
[qQ]|[qQ][uU][iI][tT]) exit 1 ;;
esac
}
while $GO; do
OE_USER=
while (id -u $OE_USER > /dev/null 2>&1); do
echo "CMIT # What user will this run under?"
read -r -p "CMIT > " OE_USER
if id -u $OE_USER > /dev/null 2>&1; then
echo "CMIT # Bad User Name. Try Again"
fi
done
clear
confirm "Continue installing using '$OE_USER' as the server name?"
done
GO=true
您可以声明一个全局标志,该标志在正确答案的confirm函数中设置,也可以在confirm中使用一个return语句,该语句在while循环的条件中进行测试
还有其他选择,比如在测试用户输入后使用递归调用。这将消除while循环的需要,但也需要使初始输入成为函数。您可以使用函数的退出状态: 将“是”案例更改为执行“真”,将“否”案例更改为执行“假”。然后
您的外部while循环将永远不会中断。循环中没有break语句,循环条件为
true
。我想您可能需要条件测试confirm
调用的结果?然后您可以将true
更改为$?
,但只需确保$?
等于true
进入循环,因此在外部while循环之前添加对true
的调用。@bgoldst谢谢。在我发布这篇文章之后,我注意到了这一点。还是不敢相信这是如此明显的事情。
while true; do
# ...
if confirm "Continue installing using '$OE_USER' as the server name?"
then
break
fi
done