我想创建一个索引和值对的字符串。这将用于dialog
菜单。
declare -r -a arr=(
piano
table
chair
)
dialog
--backtitle "Launcher"
--title "App"
--ok-label 'Select'
--cancel-label "Back"
--menu "Select an application"
$dialog_height $dialog_width 4
"1" "piano"
"2" "table"
"3" "chair"
所以我希望有:
"1" "piano"
"2" "table"
"3" "chair"
从数组中自动生成。
有一个类似的问题传递一个数组到对话框菜单,我尝试了什么,我不能让它为我工作。
要在每个数组条目前自动生成标记1
,2
,3
,请使用
items=(piano table chair)
taggedItems=()
for ((i=1; i<="${#items[@]}"; ++i)); do
taggedItems+=("$i" "${items[i-1]}")
done
# then use "${taggedItems[@]}"
与您的链接awk
解决方案相反,这适用于可能包含空格,特殊符号(如*
)甚至换行符的任意项。
declare -a arr=(
''
piano
table
chair
)
unset 'arr[0]'
declare -ar arr
# Remove the echo below once ready for the fun.
echo dialog
--backtitle "Launcher"
--title "App"
--ok-label 'Select'
--cancel-label "Back"
--menu "Select an application"
$dialog_height $dialog_width 4
$(for i in "${!arr[@]}"; do echo "$i" "${arr[i]}"; done)
OPTIONS=(1 "table"
2 "piano"
3 "......")
dialog
--backtitle "Launcher"
--title "App"
--ok-label 'Select'
--cancel-label "Back"
--menu "Select an application"
$dialog_height $dialog_width 4
"${OPTIONS[@]}"
2>&1 >/dev/tty
有两种方法,使用简单数组:
#!/bin/bash
declare -r -a arr=(
piano
table
chair
)
options=$(printf '%sn' "${arr[@]}" | awk '{print v++,$arr}')
dialog
--backtitle "Test"
--title "Test"
--menu "Test"
0 0 4
$options
2>&1 >/dev/tty
或与关联数组:
#!/bin/bash
declare -r -A arr=(
piano
table
chair
)
options=$(printf '%sn' "${!arr[@]}" | awk '{print v++,$arr}')
dialog
--backtitle "Test"
--title "Test"
--menu "Test"
0 0 4
$options
2>&1 >/dev/tty
从1开始菜单编号:
#!/bin/bash
declare -r -a arr=(
piano
table
chair
)
options=$(printf '%sn' "${arr[@]}" | awk -v v=1 '{print v++,$arr}')
dialog
--backtitle "Test"
--title "Test"
--menu "Test"
0 0 4
$options
2>&1 >/dev/tty
在菜单中同时使用关联数组的键和值:
#!/bin/bash
declare -r -A arr=(
[piano]=piano
[table]=mesa
[chair]=cadeira
)
options=$(printf "%sn" "${!arr[@]} " "${arr[@]}")
dialog
--backtitle "Test"
--title "Test"
--menu "Test"
0 0 4
$options
2>&1 >/dev/tty
正确答案既可用于普通数组,也可用于关联数组,使用数字索引或关联键作为菜单键:
菜单项的普通数组,使用数字索引作为菜单键:
#!/usr/bin/env bash
arr=(
piano
table
chair
)
options=()
for k in "${!arr[@]}"; do
options+=( "$k" "${arr[$k]}" )
done
dialog
--backtitle "Test"
--title "Test"
--menu "Test"
0 0 4
"${options[@]}"
>/dev/tty 2>&1
关联数组的完整示例:
#!/usr/bin/env bash
declare -A assoc=(
[p]=piano
[t]=table
[c]=chair
)
options=()
for k in "${!assoc[@]}"; do
options+=("$k" "${assoc[$k]}")
done
choice="$(
dialog
--backtitle "Test"
--title "Test"
--menu "Test"
0 0 4
"${options[@]}"
2>&1 >/dev/tty
)"
clear
case $choice in
t)
printf %s\n "Let's set the table."
;;
p)
printf %s\n "Let's play piano."
;;
c)
printf %s\n "Let's sit dow."
;;
*)
printf %s\n "Let's decide later."
;;
esac