在脚本shell中选择多个选项?

zak*_*ter -3 bash shell sh

我想创建一个带有多选脚本的菜单.喜欢 :

1) 

2)

3)

4)

5)
Run Code Online (Sandbox Code Playgroud)

我可以在同一时间选择1,3和5.

mkl*_*nt0 5

bashselect复合命令不直接支持多种选择,但你仍然可以立足解决方案就可以了,走的,无论用户输入被记录在特殊的事实优势$REPLY变量:

#!/usr/bin/env bash

choices=( 'one' 'two' 'three' 'four' 'five' ) # sample choices
select dummy in "${choices[@]}"; do  # present numbered choices to user
  # Parse ,-separated numbers entered into an array.
  # Variable $REPLY contains whatever the user entered.
  IFS=', ' read -ra selChoices <<<"$REPLY"
  # Loop over all numbers entered.
  for choice in "${selChoices[@]}"; do
    # Validate the number entered.
    (( choice >= 1 && choice <= ${#choices[@]} )) || { echo "Invalid choice: $choice. Try again." >&2; continue 2; }
    # If valid, echo the choice and its number.
    echo "Choice #$(( ++i )): ${choices[choice-1]} ($choice)"
  done
  # All choices are valid, exit the prompt.
  break
done

echo "Done."
Run Code Online (Sandbox Code Playgroud)

至于select命令通常如何工作,只需一个选择:

  • 运行man bash并查看"复合命令"标题下的内容
  • 有关带注释的示例,请参阅此答案.

这个答案实现了如下定制逻辑:

  • select命令的指定目标变量dummy,,被忽略,$REPLY而是使用变量,因为Bash将其设置为用户输入的任何内容(未经验证).
  • IFS=', ' read -ra selChoices <<<"$REPLY" 标记用户输入的值:
    • 它通过here-string(<<<)传递给read命令
    • 使用逗号和space(,<space>)实例作为[Internal] Field Separator(IFS=...)
      • 请注意,作为副作用,用户只能使用空格来分隔他们的选择.
    • 并将生成的标记存储为array(-a)的元素selChoices; -r简单地关掉\字符的解释.在输入中
    • for choice in "${selChoices[@]}"; do 循环遍历所有标记,即用户选择的单个数字.
    • (( choice >= 1 && choice <= ${#choices[@]} )) || { echo "Invalid choice: $choice. Try again." >&2; continue 2; } 确保每个令牌有效,即它是介于1和所呈现的选择计数之间的数字.
  • echo "Choice #$(( ++i )): ${choices[choice-1]} ($choice)" 输出每个选项和选项号
    • 前缀为运行索引(i),++i使用算术扩展($((...)))递增()- 因为变量默认为0算术上下文,第一个索引输出将是1;
    • 接着是${choices[choice-1]},即由输入的数字表示的选择字符串,递减1,因为Bash数组是0基于的; 注意如何在数组下标中choice不需要$前缀,因为下标是在算术上下文中计算的(就像在里​​面一样$(( ... ))),如上所述.
    • ($choice)在括号中选择的数字终止.
  • break需要退出提示; 默认情况下,select会继续提示.