通过bash中的list传递带有空格的参数 [英] Passing arguments with spaces via list in bash
问题描述
在bash脚本中使用动态生成的参数调用某些函数很有趣.
I am interesting in calling some function using dynamically generated arguments in a bash script.
但是,如果某些参数中有空格,则似乎无效.
However, if some of the arguments had spaces, it does not seem to work.
让我们使用以下测试脚本:
Let's have this test script:
#!/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"
时,我得到以下结果:
When calling bash vv.sh "a b"
I get the following result:
$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的方法,例如结果将是:
I am expecting a way to pass the variables to uu.sh such as the result would be:
$1 -x
$2 a b
$0 uu.sh
(我可以直接通过调用 bash uu.sh -xa \ b
或 bash uu.sh -x"ab"
或 bashuu.sh -x'a b'
)
(Which I can get directly by calling bash uu.sh -x a\ b
, or bash uu.sh -x "a b"
, or bash uu.sh -x 'a b'
)
推荐答案
您应该具有这样的 vv.sh
,以便能够在 -x
之后传递所有参数.在 uu.sh
的第二个参数中:
You should have vv.sh
like this to be able to pass all the arguments after -x
in the 2nd argument to 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 [@]
然后将其用作(请参见引用的参数):
Then use it as (see quoted arguments):
bash vv.sh "a b"
...将作为输出发出:
...which will emit as output:
$1 -x
$2 a b
$0 uu.sh
这篇关于通过bash中的list传递带有空格的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!