如何在 bash 中使用 cmd 对话框创建动态多个 select 选项

how to create dynamic multiple select options using cmd dialogue in bash

我似乎无法获得为我提供多个 select 选项的对话框。

这是我试图在对话框中完成的简化版本:

Menu Selection
"Pick one or more options:"
1) Option 1
2) Option 2
3) Option 3

        <select>               <exit>

用户在 selecting:

时看到的地方
"Pick one or more options:"
 * 1) Option 1
 * 2) Option 2
 3) Option 3

            <select>               <exit>

然后在 select 上输入键后看到: "You've selected Options 1 and 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

当 运行 这个 (./menu.bash) 在 CLI 上时,我收到以下信息:

Error: Expected at least 7 tokens for --checklist, have 5. selected
Use --help to list options. selected

我错过了什么?

问题是如何构建 options 数组。由于您在代码中定义了 IFS=$'\n',因此在您查找 9 项目时,使用 options=($MENU_OPTIONS) 将仅在此数组中创建 1 项目。要解决此问题,您可以在以下代码行中用 $'\n' 替换空格:(注意:您还需要在 for choice in $choices; do ...; done 之前 unset IFS

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