我似乎无法让对话框给我多个选择选项。
这是我在对话框中尝试完成的简化版本:
Menu Selection
"Pick one or more options:"
1) Option 1
2) Option 2
3) Option 3
<select> <exit>
用户在选择时看到此内容:
"Pick one or more options:"
* 1) Option 1
* 2) Option 2
3) Option 3
<select> <exit>
然后在输入键上选择看到:“您已选择选项1和2”。
这是我到目前为止:
#!/bin/bash
#initialize
MENU_OPTIONS=
COUNT=0
IFS=$'\n'
#get menu options populated from file
for i in `cat my_input_file.log`
do
COUNT=$[COUNT+1]
MENU_OPTIONS="${MENU_OPTIONS} $i ${COUNT} off "
done
#build dialogue box with menu options
cmd=(dialog --backtitle "Menu Selection" --checklist "Pick 1 or more options" 22 30 16)
options=(${MENU_OPTIONS})
choices=$("${cmd[@]}" "${options[@]}" 2>&1 1>/dev/tty)
#do something with the choices
for choice in $choices
do
echo $choice selected
done
在CLI上运行此(./menu.bash)时,我收到以下内容:
Error: Expected at least 7 tokens for --checklist, have 5. selected
Use --help to list options. selected
我错过了什么?
问题是如何构造options
数组。因为你在代码中定义了IFS=$'\n'
,所以当你在寻找options=($MENU_OPTIONS)
项时,使用1
将只在这个数组中创建9
项。要解决此问题,您可以在以下代码行中用$'\ n'替换空格:(注意:您还需要在unset IFS
之前使用for choice in $choices; do ...; done
)
MENU_OPTIONS="${MENU_OPTIONS} $i ${COUNT} off "
至
MENU_OPTIONS="${MENU_OPTIONS}"$'\n'${COUNT}$'\n'$i$'\n'off
或者更改代码以设置options
数组,例如:
#!/bin/bash
#initialize
COUNT=0
while IFS=$'\n' read -r opt; do
COUNT=$(( COUNT+1 ))
options+=($COUNT "$opt" off)
done <my_input_file.log
#build dialogue box with menu options
cmd=(dialog --backtitle "Menu Selection" --checklist "Pick 1 or more options" 22 30 16)
choices=($("${cmd[@]}" "${options[@]}" 2>&1 1>/dev/tty))
for choice in "${choices[@]}"; do
echo "$choice selected"
done