在使用“declare”赋值时如何保留数组元素中的空格?

时间:2017-03-01 22:16:29

标签: arrays bash unix scripting

我想将一个字符串列表分配给一个数组。这些字符串包含重要的尾随空格,我想保留它们。如下所示,当我单独分配数组元素时,会保留空格。但是当我使用“declare”命令分配数组元素时,空格会丢失。一个尴尬的解决方案是使用“\”来逃避每个空间。有没有更好的方法,或者我缺少一些语法魔法?

代码:

echo "This does what I want:"
array1[0]="foo   "
array1[1]="bar   "

for element in "${array1[@]}"
do
  echo "${element}x"
done

echo "This makes me sad:"
declare -a array2=("foo   " "bar   ")

for element in "${array2[@]}"
do
  echo "${element}x"
done

echo "This too:"
declare -a array3=('foo   ' 'bar   ')

for element in "${array3[@]}"
do
  echo "${element}x"
done

echo "An awkward solution:"
declare -a array4=("foo\ \ \ " "bar\ \ \ ")

for element in "${array4[@]}"
do
  echo "${element}x"
done

输出:

This does what I want:
foo   x
bar   x
This makes me sad:
foox
barx
This too:
foox
barx
An awkward solution:
foo   x
bar   x

1 个答案:

答案 0 :(得分:1)

我的测试符合评论:这是旧版本bash中的一个错误,修复版本在2.05b.0和3.2.57之间。但即使在旧版本中,如果将声明与赋值分开,或者只是将声明作为数组隐式,它似乎也可以工作:

$ echo $BASH_VERSION
2.05b.0(1)-release
$ declare -a array1=('foo   ' 'bar   ')    # This triggers the bug
$ printf '"%s"\n' "${array1[@]}"
"foo"
"bar"
$ declare -a array2
$ array2=('foo   ' 'bar   ')    # Separate declaration - this works
$ printf '"%s"\n' "${array2[@]}"
"foo   "
"bar   "
$ array3=('foo   ' 'bar   ')    # Implicit declaration - also works
$ printf '"%s"\n' "${array3[@]}"
"foo   "
"bar   "