通过bash中的列表传递带空格的参数

时间:2017-04-06 17:32:27

标签: linux bash shell

我很有兴趣在bash脚本中使用动态生成的参数来调用某个函数。

但是,如果某些参数有空格,则它似乎不起作用。

我们有这个测试脚本:

#!/bin/bash
# file uu.sh
[[ -z $1 ]] || echo '$1' $1
[[ -z $2 ]] || echo '$2' $2
[[ -z $3 ]] || echo '$3' $3
[[ -z $4 ]] || echo '$4' $4
[[ -z $5 ]] || echo '$5' $5
[[ -z $6 ]] || echo '$6' $6
[[ -z $7 ]] || echo '$7' $7
[[ -z $8 ]] || echo '$8' $8
[[ -z $9 ]] || echo '$9' $9
[[ -z $0 ]] || echo '$0' $0

我的任何剧本:

#!/bin/bash
# file vv.sh
ARR=(-x)
ARR+=($1)
ARR+=("$1")
ARR+=("'$1'")
ARR+=("\"$1\"")
bash uu.sh ${ARR[*]}
echo
bash uu.sh "${ARR[*]}"

调用bash vv.sh "a b"时,我得到以下结果:

$2 -x
$2 a
$3 b
$4 a
$5 b
$6 'a
$7 b'
$8 "a
$9 b"
$0 uu.sh

$1 -x a b a b 'a b' "a b"
$0 uu.sh

我期待一种将变量传递给uu.sh的方法,例如结果将是:

$1 -x
$2 a b
$0 uu.sh

(我可以通过致电bash uu.sh -x a\ bbash uu.sh -x "a b"bash uu.sh -x 'a b'直接与我联系)

3 个答案:

答案 0 :(得分:3)

您应该vv.sh这样才能将第二个参数中-x之后的所有参数传递给uu.sh

#!/bin/bash
# file vv.sh
ARR=(-x)    # initialize array with "-x" as first element
ARR+=("$1") # append 1st argument in second element of array
bash uu.sh "${ARR[@]}" # call uu.sh with quoted and [@]

然后将其用作(参见引用的参数):

bash vv.sh "a b"

...将作为输出发出:

$1 -x
$2 a b
$0 uu.sh

答案 1 :(得分:3)

以下是$*$@之间的区别,并且您应该始终引用变量(除非您知道为什么不需要):)

#uu.sh
[[ -z "$1" ]] || echo '$1' "$1"
[[ -z "$2" ]] || echo '$2' "$2"
[[ -z "$3" ]] || echo '$3' "$3"
[[ -z "$4" ]] || echo '$4' "$4"
[[ -z "$5" ]] || echo '$5' "$5"
[[ -z "$6" ]] || echo '$6' "$6"
[[ -z "$7" ]] || echo '$7' "$7"
[[ -z "$8" ]] || echo '$8' "$8"
[[ -z "$9" ]] || echo '$9' "$9"
[[ -z "$0" ]] || echo '$0' "$0"

vv.sh

ARR=(-x)
ARR+=($1)
ARR+=("$1")
ARR+=("'$1'")
ARR+=("\"$1\"")

echo 'using quoted ARR[@]'
printf "=%s=\n" "${ARR[@]}"

echo 'using unquoted ARR[@]'
printf "=%s=\n" ${ARR[@]}

echo 'using quoted ARR[*]'
printf "=%s=\n" "${ARR[*]}"

echo 'using unquoted ARR[*]'
printf "=%s=\n" ${ARR[*]}

echo "running UU"
bash uu.sh "${ARR[@]}"

输出:

using quoted ARR[@]
=-x=
=A=
=B=
=A B=
='A B'=
="A B"=
using unquoted ARR[@]
=-x=
=A=
=B=
=A=
=B=
='A=
=B'=
="A=
=B"=
using quoted ARR[*]
=-x A B A B 'A B' "A B"=
using unquoted ARR[*]
=-x=
=A=
=B=
=A=
=B=
='A=
=B'=
="A=
=B"=
running UU
$1 -x
$2 A
$3 B
$4 A B
$5 'A B'
$6 "A B"
$0 uu.sh

答案 2 :(得分:3)

"${array[*]}""$*"扩展为单个词,其中数组成员或位置参数与空格连接。这几乎从来没用过。相反,请使用"${array[@]}""$@",它会将所有数组成员展开以分隔单词。 (请参阅手册中的ArraysSpecial parameters。)

所以当你执行bash uu.sh "${ARR[*]}"时,命令会传递一个字符串作为参数,而bash uu.sh ${ARR[*]}则没有引号,所以数组的所有内容都为get split on whitespace