我想暂停shell脚本中的输入,并提示用户进行选择。标准的是、否或取消类型问题。如何在典型的bash提示符中完成此操作?
当前回答
要获得像inputbox这样的漂亮ncurses,请使用如下命令对话框:
#!/bin/bash
if (dialog --title "Message" --yesno "Want to do something risky?" 6 25)
# message box will have the size 25x6 characters
then
echo "Let's do something risky"
# do something risky
else
echo "Let's stay boring"
fi
默认情况下,对话框包至少在SUSE Linux上安装。看起来像:
其他回答
要获得像inputbox这样的漂亮ncurses,请使用如下命令对话框:
#!/bin/bash
if (dialog --title "Message" --yesno "Want to do something risky?" 6 25)
# message box will have the size 25x6 characters
then
echo "Let's do something risky"
# do something risky
else
echo "Let's stay boring"
fi
默认情况下,对话框包至少在SUSE Linux上安装。看起来像:
您可以在读取时使用默认REPLY,将其转换为小写,并使用表达式与一组变量进行比较。该脚本还支持ja/si/oui
read -rp "Do you want a demo? [y/n/c] "
[[ ${REPLY,,} =~ ^(c|cancel)$ ]] && { echo "Selected Cancel"; exit 1; }
if [[ ${REPLY,,} =~ ^(y|yes|j|ja|s|si|o|oui)$ ]]; then
echo "Positive"
fi
您可以编写一个函数来测试:
confirm() {
local ans IFS=;
while read -rp "$1" -n1 ans;
do printf '\n';
case $ans in [Yy]) return 0;;
[Nn]) return 1;;
esac;
done;
}; ## Usage: if confirm "Are you sure? "; then ...
if confirm "Does everything look ok...reboot now? [Y/n]"; then
echo "rebooting..."
sleep 5
reboot
fi
是/否/取消
作用
#!/usr/bin/env bash
@confirm() {
local message="$*"
local result=''
echo -n "> $message (Yes/No/Cancel) " >&2
while [ -z "$result" ] ; do
read -s -n 1 choice
case "$choice" in
y|Y ) result='Y' ;;
n|N ) result='N' ;;
c|C ) result='C' ;;
esac
done
echo $result
}
用法
case $(@confirm 'Confirm?') in
Y ) echo "Yes" ;;
N ) echo "No" ;;
C ) echo "Cancel" ;;
esac
使用干净的用户输入进行确认
作用
#!/usr/bin/env bash
@confirm() {
local message="$*"
local result=3
echo -n "> $message (y/n) " >&2
while [[ $result -gt 1 ]] ; do
read -s -n 1 choice
case "$choice" in
y|Y ) result=0 ;;
n|N ) result=1 ;;
esac
done
return $result
}
用法
if @confirm 'Confirm?' ; then
echo "Yes"
else
echo "No"
fi
针对其他人:
您不需要在BASH4中指定大小写,只需使用',,'使var小写即可。此外,我强烈不喜欢将代码放在读取块内,获取结果并在读取块IMO外处理它。还包括一个“q”表示退出IMO。最后,为什么键入“yes”只需使用-n1并按y。
示例:用户可以按y/n和q退出。
ans=''
while true; do
read -p "So is MikeQ the greatest or what (y/n/q) ?" -n1 ans
case ${ans,,} in
y|n|q) break;;
*) echo "Answer y for yes / n for no or q for quit.";;
esac
done
echo -e "\nAnswer = $ans"
if [[ "${ans,,}" == "q" ]] ; then
echo "OK Quitting, we will assume that he is"
exit 0
fi
if [[ "${ans,,}" == "y" ]] ; then
echo "MikeQ is the greatest!!"
else
echo "No? MikeQ is not the greatest?"
fi