我想暂停shell脚本中的输入,并提示用户进行选择。标准的是、否或取消类型问题。如何在典型的bash提示符中完成此操作?


当前回答

您可以使用内置的read命令;使用-p选项向用户提示问题。

从BASH4开始,您现在可以使用-i建议答案:

read -e -p "Enter the path to the file: " -i "/usr/local/etc/" FILEPATH
echo $FILEPATH

(但请记住使用“readline”选项-e以允许使用箭头键进行行编辑)

如果你想要一个“是/否”的逻辑,你可以这样做:

read -e -p "
List the content of your home dir ? [Y/n] " YN

[[ $YN == "y" || $YN == "Y" || $YN == "" ]] && ls -la ~/

其他回答

用最少的行数实现这一点的最简单方法如下:

read -p "<Your Friendly Message here> : y/n/cancel" CONDITION;

if [ "$CONDITION" == "y" ]; then
   # do something here!
fi

if只是一个例子:如何处理这个变量取决于您。

read -p "Are you alright? (y/n) " RESP
if [ "$RESP" = "y" ]; then
  echo "Glad to hear it"
else
  echo "You need more bash programming"
fi

在这种情况下,我已经多次使用case语句,使用case语句是一种很好的方法。可以实现while循环,该循环模拟case块,利用布尔条件,以便更好地控制程序,并满足许多其他要求。在满足所有条件后,可以使用中断,将控制权传递回程序的主要部分。此外,为了满足其他条件,当然可以在控制结构中添加条件语句:case语句和可能的while循环。

使用案例陈述来满足您的请求的示例

#! /bin/sh 

# For potential users of BSD, or other systems who do not
# have a bash binary located in /bin the script will be directed to
# a bourne-shell, e.g. /bin/sh

# NOTE: It would seem best for handling user entry errors or
# exceptions, to put the decision required by the input 
# of the prompt in a case statement (case control structure), 

echo Would you like us to perform the option: "(Y|N)"

read inPut

case $inPut in
    # echoing a command encapsulated by 
    # backticks (``) executes the command
    "Y") echo `Do something crazy`
    ;;
    # depending on the scenario, execute the other option
    # or leave as default
    "N") echo `execute another option`
    ;;
esac

exit

这是我在脚本/函数中通常需要的:

如果按ENTER键,默认答案为“是”也接受z(如果你在QWERTZ布局上搞混了)接受其他语言(“ja”、“Oui”、…)如果您在函数内部,请处理正确的出口

while true; do
    read -p "Continue [Y/n]? " -n 1 -r -e yn
    case "${yn:-Y}" in
        [YyZzOoJj]* ) echo; break ;;
        [Nn]* ) [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1 ;; # handle exits from shell or function but don't exit interactive shell
        * ) echo "Please answer yes or no.";;
    esac
done
echo "and off we go!"

您可以在读取时使用默认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