String 如何在bash中保留空间分隔的组

String 如何在bash中保留空间分隔的组,string,bash,String,Bash,我想构建一个包含引用的词组的字符串。 这些组应转到同一个函数参数。 我试着玩数组。 从字面上看,构建的数组是有效的,但我仍然希望找到 对裸字符串的神奇语法破解 # literal array LA=(a "b c") function printArgs() { # function should print 2 lines while [ $# -ne 0 ] ; do print $1 ; shift; done } printArgs "${LA[@]}" # works fine

我想构建一个包含引用的词组的字符串。 这些组应转到同一个函数参数。 我试着玩数组。 从字面上看,构建的数组是有效的,但我仍然希望找到 对裸字符串的神奇语法破解

# literal array
LA=(a "b c")

function printArgs() { # function should print 2 lines
  while [ $# -ne 0 ] ; do print $1 ; shift; done
}

printArgs "${LA[@]}" # works fine
# but how to use string to split only unquoted spaces?

LA="a \"b c\""
printArgs "${LA[@]}" # doesn't work :(
LA=($LA)
printArgs "${LA[@]}" # also doesn't work :(
bash数组有一个问题,它们不能通过传送带传送
-(echo/$())

肮脏的方法是:

#!/bin/bash
LA=(a "b  c")

function printArgs()
{ # function should print 2 lines
  while [ $# -ne 0 ]
  do
   echo "${1//_/ }" #Use parameter expansion to globally replace '_' with space
  #Do double quote as we don't want to have word splitting
   shift
  done
}

printArgs "${LA[@]}" # works fine

LA="a b__c" # Use a place holder '_' for space, note the two '_' for two spaces
printArgs $LA #Don't double quote '$LA' here. We wish word splitting to happen. And works fine :-)
样本输出

a
b  c
a
b  c
请注意,分组实体中的空间数将保留


旁注

在这里,占位符的选择至关重要。希望您能找到一个不会出现在实际字符串中的字符串。

当然不会。如果可能的话,就不需要阵列了。