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

问题描述

我需要将数组的每个元素添加到对话框菜单中。问题在于,使用 $ {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 [@]} 一个单词一个单词的分隔符,得到一个数字和字符串的序列。

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

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