首页 > 解决方案 > 变量作为多个命令参数忽略 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;'开始; 图片; 作为; 压倒一切'; ...

再多的报价交换都没有给我带来梦寐以求的结果。

标签: bashvariablesparameters

解决方案


参数扩展后,结果中的任何引号都被视为文字字符,而不是转义空格的语法。创建值列表的正确方法是使用数组,它充当第二层引用以允许每个元素中存在空格。作为奖励,数组分配还允许更易读的格式。

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[@]}"

推荐阅读