简体   繁体   中英

Variable as multiple command parameters ignore quotes in Bash

I want to insert a variable (basically a read text file) into a command body as multiple parameters, but this doesn't work because the variable is not resolved properly.

My variable

MAIN_MENU="1 'Create new image' 2 'Start image as overriding' 3 'Start image as snapshot' 4 'Install OS' 5 'Settings'"

Echoes:

echo $MAIN_MENU
1 'Create_new_image' 2 'Start_image _as_overriding' 3 'Start _image_as_snapshot' 4 'Install_OS' 5 'Settings'

Which is what I expect and if I copy paste the echo result (by hand) to command parameters like below, it works.

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'

In this case, parameters are ... 1; Create new image; 2; Start image as overriding ...

However, when I insert the parameters as a variable, it ignores the single quotes completely..

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

Basically leaving single quotes there, but also separating the parameters by spaces..

In this case, parameters are ... 1; 'Create; new; image'; 2; 'Start; image; as; overriding'; ...

No amount of quote swapping resulted in coveted results for me.

After parameter expansion, any quotes in the result are treated as literal characters, not syntax for escaping whitespace. The correct way to create a list of values is to use an array, which acts as a second layer of quoting to allow whitespace in each element. As a bonus, array assignments also allow for more readable formatting.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM