Linux - case 命令

Linux - case 命令

如何在菜单列表中包含空格或制表符?

    PS3='Please enter your choice: '
    options=("Option 1" "Option 2" "Quit")
    select opt in "${options[@]}"
    do
      case $opt in
         "Option 1")
            echo "Your choise is 1"
            ;;
         "Option 2")
            echo "Your choise is 2"
            ;;
         "Quit")
            break
            ;;
         *) echo "Invalid option;;
      esac
    done

我得到了这个:

[user@Server:/home/user] ./test.sh
1) Option 1
2) Option 2
3) Option 3
4) Quit
Please enter your choice:

但我想要这样的东西:

[user@Server:/home/user] ./test.sh
   1) Option 1
   2) Option 2
   3) Option 3
   4) Quit
Please enter your choice:

有想法吗?

答案1

手动(粗略地)重新实现并微调显示并不太难select,至少只要您没有太多选项需要多列列表。

#!/bin/bash

# print the prompt from $1, and a menu of the other arguments
choose() {
    local prompt=$1
    shift
    local i=0
    for opt in "$@"; do
        # we have to do the numbering manually...
        printf "  %2d) %s\n" "$((i += 1))" "$opt"
    done
    read -p "$prompt: "
}

options=("Foo" "Bar" "Quit")
while choose 'Please enter your choice'  "${options[@]}"; do
    case $REPLY in
    1) echo "you chose 'foo'" ;;
    2) echo "you chose 'bar'";;
    3) echo 'you chose to quit'; break;;
    *) echo 'invalid choice';;
    esac
done

当然,这可以扩展到考虑数组键(索引),并将它们呈现为菜单中的选项,而不是运行计数器。

答案2

select显示菜单的语句不允许bash为菜单指定缩进。


只是对代码的评论:通常让语句case作用于$REPLY而不是作用于具有所选字符串的变量更容易。它使您不必输入两次字符串。

例如

select opt in "${options[@]}"
do
  case $REPLY in
     1)
        echo "Your choice is 1"
        ;;
     2)
        echo "Your choice is 2"
        ;;
     3)
        break
        ;;
     *) echo 'Invalid option' >&2
  esac
done

或者,对于这个具体的例子,

select opt in "${options[@]}"
do
  case $REPLY in
     [1-2])
        printf 'Your choice is %s\n' "$REPLY"
        ;;
     3)
        break
        ;;
     *) echo 'Invalid option' >&2
  esac
done

相关内容