Brace expansion from a variable in Bash

我是研究僧i 提交于 2019-12-20 03:49:08

问题


I would like to expand a variable in Bash. Here's my example:

variable="{1,2,3}"
echo $variable

Expected output:

1 2 3

Actual output:

{1,2,3}

回答1:


The expansion doesn't work because of the order in which bash performs command-line expansion. If you read the man page you'll see the order is:

  1. Brace expansion
  2. Tilde expansion
  3. Parameter expansion
  4. Command substitution
  5. Arithmetic expansion
  6. Process substitution
  7. Word splitting
  8. Pathname expansion
  9. Quote removal

Parameter expansion happens after brace expansion, which means you can't put brace expansions inside variables like you're trying.

But never fear, there's an answer! To store a list of numbers in a variable, you can use an array.

variable=(1 2 3)
echo "${variable[@]}"



回答2:


This won't work first because double-quotes suppress brace expansion:

variable="{1,2,3}"

This still won't work because bash will not assign a list to a variable:

variable={1,2,3}

The solution is to assign your list to an array:

$ variable=( {1,2,3} )
$ echo "${variable[@]}"
1 2 3


来源:https://stackoverflow.com/questions/30064674/brace-expansion-from-a-variable-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!