我的这个脚本运行得很好,但是如果输入错误,我想重新运行该脚本,该怎么办?
#! /bin/bash
#! userInput - a script that reads in text and outputs it immediately
echo "Would you like to input some text? Y/N"
read request
if [[ $request = Y ]]; then
echo "Please input some text"
read input
echo $input
elif [[ $request = N ]]; then
echo "Thank You"
else
echo "Invalid Input - Please Input Y for yes or N for no"
fi
答案1
这就是select
目的。
PS3="Would you like to input some text? <Y/N> ]"
select choice in "Y" "N"; do
case $choice in
"Y")
echo -n "Please input some text >"
read input
echo "$input"
break
;;
"N")
echo "Very well."
break
;;
*)
echo "Invalid response."
;;
esac
done
答案2
我建议您组织控制流来对您要解决的问题进行建模。你想在用户不想退出时查看,而不是永远查看:
#!/bin/bash
echo -n "Would you like to input some text (Y/N): "
read request
while [[ "${request}" != "N" ]]; do
if [[ "${request}" == "Y" ]]; then
echo -n "Please input some text: "
read input
echo "You entered '${input}'"
else
echo "Invalid input: '${request}'"
fi
echo -n "Would you like to input some text (Y/N): "
read request
done
echo "Thank you"
答案3
怎么样
#!/bin/bash
# userInput - a script that reads in text and outputs it immediately
while true; do
echo "Would you like to input some text? Y/N"
read request
if [[ $request = Y ]]; then
echo "Please input some text"
read input
echo $input
break
elif [[ $request = N ]]; then
echo "Thank You"
break
else
echo "Invalid Input - Please Input Y for yes or N for no"
fi
done
答案4
否则,如果您确实想重新运行脚本:
else
exec $0