将数组的每个元素作为菜单分别添加到 DIALOG 命令中

Add each element of the array separately to the DIALOG command as a menu

我需要将数组的每个元素添加到对话框菜单中。问题是使用命令 $ {array [@]} 对话框将每个单词识别为一个元素。看:

第一次尝试:添加带空格的元素

list=('Google Chrome' 'Brackets' 'Visual Studio') # my list
declare -a dia # dialog array

for index in ${!list[@]}; do # for each index in the list
    dia[${#dia[@]}]=$index # add index
    dia[${#dia[@]}]=${list[$index]} #add element
done

dialog --menu "MENU" 0 0 0 $(echo ${dia[@]})

# Format: dialog --menu "TITLE" 0 0 0 'Index1' 'Element1' 'Index2' 'Element2'...

# dia[0] = 0
# dia[1] = 'Google Chrome' 
# dia[1] = 1 
# dia[2] = 'Brackets'...

PRINT: first attempt

我这样做是为了避免处理每个单词,用${list[@]}的return逐字分开,得到数字和字符串的序列。

第二次尝试:将“ ”替换为“-”

for index in ${!list[@]}; do
    dgl[${#dgl[@]}]=$index 
    dgl[${#dgl[@]}]=${list[$index]/' '/'-'}
done

PRINT: Second attempt

我认为正在发生的事情

我相信在将数组元素传递给 DIALOG 命令时,它会考虑空格(例如“Google Chrome”)。有没有办法让我用空格显示这个?

对您的代码进行了所有必要的更改,使其现在可以按预期工作。

#!/usr/bin/env bash

list=('Google Chrome' 'Brackets' 'Visual Studio') # my list
declare -a dia=()                                 # dialog array

for index in "${!list[@]}"; do # for each index in the list
  dia+=("$index" "${list[index]}")
done

choice=$(
  dialog --menu "MENU" 0 0 0 "${dia[@]}" \
    3>&1 1>&2 2>&3 3>&- # Swap stdout with stderr to capture returned dialog text
)
dialog_rc=$? # Save the dialog return code

clear # restore terminal background and clear

case $dialog_rc in
  0)
    printf 'Your choice was: %s\n' "${list[choice]}"
    ;;
  1)
    echo 'Cancelled menu'
    ;;
  255)
    echo 'Closed menu without choice'
    ;;
  *)
    printf 'Unknown return code from dialog: %d\n' $dialog_rc >&2
    ;;
esac