Bash 带空格的命令行参数

Bash 带空格的命令行参数,bash,shell,arguments,spaces,Bash,Shell,Arguments,Spaces,使用包含空格的命令行参数调用shell脚本通常通过将参数括在引号中来解决: getParams.sh 'one two' 'foo bar' 产生: one two foo bar getParams.sh: while [[ $# > 0 ]] do echo $1 shift done 但是,如果首先定义一个shell变量来保存参数值,例如: args="'one two' 'foo bar'" 那么,为什么: getParams.sh $args 无法识别包

使用包含空格的命令行参数调用shell脚本通常通过将参数括在引号中来解决:

getParams.sh 'one two' 'foo bar'
产生:

one two
foo bar
getParams.sh:

while [[ $# > 0 ]]
do
    echo $1
    shift
done
但是,如果首先定义一个shell变量来保存参数值,例如:

args="'one two' 'foo bar'"
那么,为什么:

getParams.sh $args
无法识别包含分组参数的单引号?输出为:

'one
two'
'three
four'
如何将包含空格的命令行参数存储到变量中,以便在调用getParams时,按照原始示例中引用的参数对参数进行分组?

使用数组:

args=('one two' 'foo bar')

getParams.sh "${args[@]}"
使用
args=“'one-two'foo-bar'”
不起作用,因为单引号在双引号内时保留其文字值

要在参数中保留多个空格(并处理特殊字符,如
*
),应引用变量:

while [[ $# -gt 0 ]]
do
    echo "$1"
    shift
done

shell在扩展变量之前解析引号(以及转义和其他一些东西),因此在变量中加引号与在命令行中直接使用引号不同。请参见
[$#>0]
执行字符串比较
[$#-gt 0]
($#>0))
甚至
而($)
谢谢@user000001。这基本上是有效的。剩下的问题是多个空间被替换为一个空间。如果某些字符串嵌入了多个相邻空格,如何保留所有空格?@tgoneil:您应该引用变量(
“$1”
)以在echo中保留多个空格。啊哈!成功了!谢谢@user000001!