这可能吗(bash v5.0.3)?
我想使用关联数组的键动态填充选择列表(以便进一步重用代码和脚本自动化)。有些键只需要空格。我似乎已经将我的问题隔离到了choices="${!playlist_url[@]}" # Need quoted key expansion here, but choices="${!playlist_url[@]@Q} does nothing"
我的脚本如下所示,显示一个选择选项,所有上传者都作为“1)”后面的串联打印。我能完成的最好的事情是将键转储到 $choices 中的单引号,并在引号之外退出,即choices=("Quit ${choices@Q}")
脚本
# Creates the array
declare -A playlist_url
# Sets the field separator to comma and reads in the uploader & url
## EXAMPLES: from ~/.config/youtube-dl/playlists-hcs7 ##
# UploaderName,https://www.youtube.com/playlist?list=xx...xx
# Uploader Name,https://www/youtube.com/playlist?list=xx...xx
# Up Loader Name,https://www/youtube.com/playlist?list=xx...xx
while IFS=\, read -p "uploader,url" uploader url
do
playlist_url[$uploader]="$url"
done <~/.config/youtube-dl/playlists-hcs7
#unset IFS <--Ignore my trying to better understand the IFS
#IFS= <--" "
choices=${!playlist_url[@]} # Need quoted key expansion here (I think!)
choices=("Quit ${choices}") # Prepending 'Quit' for case break below
clear
PS3="Make a selection: "
select option in "$choices";
do
case $option in
"Quit")
echo "Exiting."
break
;;
*)
echo "Debug: $option"
# Do stuff
;;
esac
done
使用的资源
即链接答案中的此编辑:
编辑:差不多 5 年后,自从我回答这个问题以来,bash 4.4 已经发布了。它有“${var@Q}”扩展,它引用变量,以便它可以被 bash 解析回来。