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

问题描述 投票:0回答:1

我似乎无法让对话框给我多个选择选项。

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

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

我错过了什么?

bash dialog options
1个回答
1
投票

问题是如何构造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
© www.soinside.com 2019 - 2024. All rights reserved.