使用 `select` 命令在 Bash 中打印菜单

Sum*_*mod 12 bash shell-script select

我正在尝试使用该select命令实现一个简单的菜单。脚本(用于测试目的)如下:

#!/bin/bash
echo "*******************"
PS3='Select an option and press Enter: '
options=("apache" "named" "sendmail")
select opt in "${options[@]}"
do
  case $opt in
        "apache")
          date
          ;;
        "named")
          echo "test"
          ;;
        "sendmail")
          echo "test 2"
          ;;
        *) echo "invalid option";;
  esac
done
echo "*********************"
Run Code Online (Sandbox Code Playgroud)

该脚本无法识别我提供的任何有效输入,并始终打印“无效选项”消息。这个脚本做错了什么?

gle*_*man 13

select 显示的菜单如下所示:

1) apache
2) named
3) sendmail
Select an option and press Enter: 
Run Code Online (Sandbox Code Playgroud)

此时,您输入“1”或“2”或“3”:您不键入单词。

此外,select将循环直到它看到一个break命令,所以你想要这个:

  case $opt in
        "apache")
          date
          break
          ;;
        "named")
          echo "test"
          break
          ;;
        "sendmail")
          echo "test 2"
          break
          ;;
        *) echo "invalid option";;
  esac
Run Code Online (Sandbox Code Playgroud)

如果你想允许用户输入数字或单词,你可以这样写:

select opt in "${options[@]}"; do
  case "$opt,$REPLY" in
    apache,*|*,apache)     do_something; break ;;
    named,*|*,named)       do_something; break ;;
    sendmail,*|*,sendmail) do_something; break ;;
  esac
done
Run Code Online (Sandbox Code Playgroud)

逗号没有语法意义,它只是为了能够在 $REPLY 变量(这是用户实际输入的)或 $opt 变量上进行模式匹配