【发布时间】:2022-12-17 11:04:54
【问题描述】:
如果用户输入的响应与允许的选择不匹配,但第二次输入正确的响应,我试图让这个脚本循环并重新启动。我尝试使用 continue,但它会无限循环。有什么想法吗?
`
#!/bin/bash
#Obtaing user selection and input
echo " Gathering list of users on this machine..."
sleep 2
echo "$( ls /Users )"
echo "From the list above, which user did you want to work with?"
read userSelection
echo "What is that user's password?"
#Hiding User's Password
stty -echo
read userSelectionPassword
stty echo
echo "Did you want [enable], [disable], or check the current [status] of Secure Token for $userSelection?"
read taskSelection
#Converting input to lowercase
taskSelectionLower=$(echo $taskSelection | tr '[:upper:]' '[:lower:]')
#Running commands
while [ true ]
do
if [[ $taskSelectionLower == "enable" ]]; then
echo "Enabling..."
echo "$(sysadminctl -adminUser AdminUser -adminPassword AdminPass -secureTokenOn $userSelection -password $userSelectionPassword)"
break
elif [[ $taskSelectionLower == "status" ]]; then
echo "Displaying $userSelection current Secure Token status..."
echo "$( sysadminctl -secureTokenStatus $userSelection )"
break
elif [[ $taskSelectionLower == "disable" ]]; then
echo "Disabling..."
echo "$(sysadminctl -adminUser AdminUser -adminPassword AdminPass -secureTokenOff $userSelection -password $userSelectionPassword)"
break
else
echo "Incorrect selection made..."
echo "Did you want [enable], [disable], or check the current [status] of Secure Token for $userSelection?"
read taskSelection
exit
fi
done
`
尝试在条件结束时使用 continue,但无限循环。
预期结果是 for 循环重新启动,允许用户输入正确的响应并获得正确的输出。
【问题讨论】:
-
[ true ]总是成功,因为true是一个非空字符串。while [ false ]; do的工作方式完全相同。你可以执行命令true和while true; do,或者使用总是成功的标准命令::while :; do。 -
您正在读取
taskSelection的新值,但永远不会重新定义taskSelectionLower的值,这是您所有检查所查看的内容。 -
(无论如何,
exit会导致您的脚本退出而根本不重复循环。) -
@chepner 谢谢你就是这样!!!!现在我必须弄清楚如何实现一个列表来存储系统返回的值。祝我好运!!
标签: bash if-statement while-loop scripting applescript