我想创建一个带有多选脚本的菜单.喜欢 :
1) 
2)
3)
4)
5)
我可以在同一时间选择1,3和5.
bash的select复合命令不直接支持多种选择,但你仍然可以立足解决方案就可以了,走的,无论用户输入被记录在特殊的事实优势$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."
至于select命令通常如何工作,只需一个选择:
man bash并查看"复合命令"标题下的内容这个答案实现了如下定制逻辑:
select命令的指定目标变量dummy,,被忽略,$REPLY而是使用变量,因为Bash将其设置为用户输入的任何内容(未经验证).IFS=', ' read -ra selChoices <<<"$REPLY" 标记用户输入的值:
<<<)传递给read命令,<space>)实例作为[Internal] Field Separator(IFS=...)
-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会继续提示.| 归档时间: | 
 | 
| 查看次数: | 923 次 | 
| 最近记录: |