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


当前回答

使用PyInquirer的一行python替代方案

python3 -c 'import PyInquirer; print(PyInquirer.prompt([{"type":"confirm", "message":"Do you want to continue?", "name":"r"}]).get("r"))'

它支持yes/no/cancel(intr,CTRL+C)。

其他回答

受到@Mark和@Myrdin的回答的启发,我创建了一个通用提示的函数

uniprompt(){
    while true; do
        echo -e "$1\c"
        read opt
        array=($2)
        case "${array[@]}" in  *"$opt"*) eval "$3=$opt";return 0;; esac
        echo -e "$opt is not a correct value\n"
    done
}

这样使用:

unipromtp "Select an option: (a)-Do one (x)->Do two (f)->Do three : " "a x f" selection
echo "$selection"
inquire ()  {
  echo  -n "$1 [y/n]? "
  read answer
  finish="-1"
  while [ "$finish" = '-1' ]
  do
    finish="1"
    if [ "$answer" = '' ];
    then
      answer=""
    else
      case $answer in
        y | Y | yes | YES ) answer="y";;
        n | N | no | NO ) answer="n";;
        *) finish="-1";
           echo -n 'Invalid response -- please reenter:';
           read answer;;
       esac
    fi
  done
}

... other stuff

inquire "Install now?"

...

这个问题有很多很好的答案,但从我看来,没有一个是我的理想,那就是:

简单一点,只需要几行外壳使用单个y/n键(无需按enter键)如果只按回车键,则默认为yes也可以使用大写的Y/N

这是我的版本,它具有这些财产:

read -n1 -p "Continue? (Y/n) " confirm

if ! echo $confirm | grep '^[Yy]\?$'; then
  exit 1
fi

如果要在两个分支上运行代码,可以修改该条件,使其仅在“yes”上运行(只需删除if语句中的!)或添加else。

在这种情况下,我已经多次使用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

这是我整理的东西:

#!/bin/sh

promptyn () {
    while true; do
        read -p "$1 " yn
        case $yn in
            [Yy]* ) return 0;;
            [Nn]* ) return 1;;
            * ) echo "Please answer yes or no.";;
        esac
    done
}

if promptyn "is the sky blue?"; then
    echo "yes"
else
    echo "no"
fi

我是一个初学者,所以要谨慎对待,但它似乎奏效了。