bash:在"中选择"提示

时间:2017-03-14 14:51:45

标签: bash user-input interactive

我在这样的bash脚本中提示问题:

optionsAudits=("Yep" "Nope")
    echo "Include audits?"
    select opt in "${optionsAudits[@]}"; do
        case $REPLY in
            1) includeAudits=true; break ;;
            2) includeAudits=false; break ;;
            "\n") echo "You pressed enter"; break ;; # <--- doesn't work
            *) echo "What's that?"; exit;;
        esac
    done

按下输入后,如何选择默认选项? "\n"案例没有捕获回车键。

4 个答案:

答案 0 :(得分:6)

您的问题是由于select将忽略空输入。对于您的情况,read会更合适,但您将失去为自动菜单创建提供的实用程序select

要模仿select的行为,你可以这样做:

#!/bin/bash
optionsAudits=("Yep" "Nope")
while : #infinite loop. be sure to break out of it when a valid choice is made
do
    i=1
    echo "Include Audits?"
    #we recreate manually the menu here
    for o in  "${optionsAudits[@]}"; do
        echo "$i) $o"
        let i++
    done

    read reply
    #the user can either type the option number or copy the option text
    case $reply in
        "1"|"${optionsAudits[0]}") includeAudits=true; break;;
        "2"|"${optionsAudits[1]}") includeAudits=false; break;;
        "") echo "empty"; break;;
        *) echo "Invalid choice. Please choose an existing option number.";;
    esac
done
echo "choice : \"$reply\""

答案 1 :(得分:4)

通过背景信息以及允许空输入的通用,可重复使用的自定义select实现来补充Aserre's helpful answer,它解释了您的代码问题并提供了有效的解决方法

背景资料

明确拼写: select 本身忽略空输入(只需按 Enter ),只需重新输入-prompts - 用户代码甚至无法在响应中运行。

事实上, select使用空字符串向用户代码发出无效选项被输入的信号。
也就是说,如果输出变量 - $opt,在这种情况下 - 在select语句中为空,则意味着用户输入了无效的选择索引。

输出变量会收到所选选项的文字 - 在这种情况下为'Yep''Nope' - 不是索引 由用户输入。

(相比之下,您的代码会检查$REPLY而不是输出变量,其中包含用户输入的内容, index 一个有效的选择,但可能包含额外的前导和尾随空格。)

请注意如果您没有想要允许空输入,您可以 只需在提示文字中向用户指出 ^C Ctrl + C )可用于中止提示

通用自定义select函数,也接受空输入

以下函数非常接近select所做的事情,同时也允许空输入(只需按 Enter )。请注意,该函数拦截无效输入,打印警告并重新提示:

# Custom `select` implementation that allows *empty* input.
# Pass the choices as individual arguments.
# Output is the chosen item, or "", if the user just pressed ENTER.
# Example:
#    choice=$(selectWithDefault 'one' 'two' 'three')
selectWithDefault() {

  local item i=0 numItems=$# 

  # Print numbered menu items, based on the arguments passed.
  for item; do         # Short for: for item in "$@"; do
    printf '%s\n' "$((++i))) $item"
  done >&2 # Print to stderr, as `select` does.

  # Prompt the user for the index of the desired item.
  while :; do
    printf %s "${PS3-#? }" >&2 # Print the prompt string to stderr, as `select` does.
    read -r index
    # Make sure that the input is either empty or that a valid index was entered.
    [[ -z $index ]] && break  # empty input
    (( index >= 1 && index <= numItems )) 2>/dev/null || { echo "Invalid selection. Please try again." >&2; continue; }
    break
  done

  # Output the selected item, if any.
  [[ -n $index ]] && printf %s "${@: index:1}"

}

您可以按如下方式调用它:

# Print the prompt message and call the custom select function.
echo "Include audits (default is 'Nope')?"
optionsAudits=('Yep' 'Nope')
opt=$(selectWithDefault "${optionsAudits[@]}")

# Process the selected item.
case $opt in
  'Yep') includeAudits=true; ;;
  ''|'Nope') includeAudits=false; ;; # $opt is '' if the user just pressed ENTER
esac

可选阅读:原始代码的更惯用版本

注意:此代码并未解决问题,但显示了select语句的更惯用的用法;与原始代码不同,如果进行了无效选择,此代码会重新显示提示:

optionsAudits=("Yep" "Nope")
echo "Include audits (^C to abort)?"
select opt in "${optionsAudits[@]}"; do
    # $opt being empty signals invalid input.
    [[ -n $opt ]] || { echo "What's that? Please try again." >&2; continue; }
    break # a valid choice was made, exit the prompt.
done

case $opt in  # $opt now contains the *text* of the chosen option
  'Yep')
     includeAudits=true
     ;;
  'Nope') # could be just `*` in this case.
     includeAudits=false
     ;;
esac

注意:

  • case语句被移出select语句,因为后者现在保证只能进行有效输入。

  • case语句测试输出变量$opt)而不是原始用户输入($REPLY),并且该变量包含选择文本,而不是索引

答案 2 :(得分:2)

更新回答:

echo "Include audits? 1) Yep, 2) Nope"
read ans
case $ans in
    Yep|1  )  echo "yes"; includeAudits=true; v=1 ;;
    Nope|2 )  echo "no"; includeAudits=false; v=2 ;;
    ""     )  echo "default - yes"; includeAudits=true; v=1 ;;
    *      )  echo "Whats that?"; exit ;;
esac

接受"Yep""1""enter"选择是,并接受"Nope""2"取消否,并抛弃其他任何内容。它还将v设置为1或2,具体取决于用户是否需要是。

答案 3 :(得分:0)

这将满足您的要求。

options=("option 1" "option 2");
while :
do
    echo "Select your option:"
    i=1;
    for opt in  "${options[@]}"; do
        echo "$i) $opt";
        let i++;
    done

    read reply
    case $reply in
        "1"|"${options[0]}"|"")
          doSomething1();
          break;;
        "2"|"${options[1]}")
          doSomething2();
          break;;
        *)
          echo "Invalid choice. Please choose 1 or 2";;
    esac
done