bash - 变量作为多个命令参数忽略 Bash 中的引号
问题描述
我想将一个变量(基本上是一个读取的文本文件)作为多个参数插入到命令体中,但这不起作用,因为变量没有正确解析。
我的变量
MAIN_MENU="1 'Create new image' 2 'Start image as overriding' 3 'Start image as snapshot' 4 'Install OS' 5 'Settings'"
回声:
echo $MAIN_MENU
1 'Create_new_image' 2 'Start_image _as_overriding' 3 'Start _image_as_snapshot' 4 'Install_OS' 5 'Settings'
这是我所期望的,如果我将回显结果(手动)复制粘贴到下面的命令参数,它就可以工作。
dialog --title "Title" --menu 'Choose operation:' 0 0 5 1 'Create new image' 2 'Start image as overriding' 3 'Start image as snapshot' 4 'Install OS' 5 'Settings'
在这种情况下,参数是 ... 1;创建新形象;2;开始图像作为覆盖 ...
但是,当我将参数作为变量插入时,它会完全忽略单引号。
MAIN_MENU="1 'Create new image' 2 'Start image as overriding' 3 'Start image as snapshot' 4 'Install OS' 5 'Settings'"
dialog --title "Title" --menu 'Choose operation:' 0 0 5 $MAIN_MENU
基本上在那里留下单引号,但也用空格分隔参数..
在这种情况下,参数是 ... 1;'创造; 新的; 图片'; 2;'开始; 图片; 作为; 压倒一切'; ...
再多的报价交换都没有给我带来梦寐以求的结果。
解决方案
参数扩展后,结果中的任何引号都被视为文字字符,而不是转义空格的语法。创建值列表的正确方法是使用数组,它充当第二层引用以允许每个元素中存在空格。作为奖励,数组分配还允许更易读的格式。
MAIN_MENU=(
1 'Create new image' # Comments can be added, as well
2 'Start image as overriding'
3 'Start image as snapshot'
4 'Install OS'
5 'Settings'
)
dialog --title "Title" --menu 'Choose operation:' 0 0 5 "${MAIN_MENU[@]}"
推荐阅读
- python - 将 kwargs 注入 Python 中的每个函数
- twitter-bootstrap - 按 ID 选择 Bootstrap 表行
- audiokit - 清晰的范围,清晰的音符(AudioKit : AKMusicTrack 功能)
- firebase - 通过 userId 从 firebase 数据库中获取数据
- python - 更改 PyCharm 中自动完成建议的顺序(输入“ak”时断点前的 args、kwargs)
- java - Spring Data JPA - 手动插入后的密钥冲突
- javascript - JavaScript 中的“({})”是什么?
- android - getTypeFace 从一个字符
- java - JavaFx:同一视图中两个(或多个)位置的相同标签
- amazon-web-services - AWS RDS 的理想设置