pass string as arguments with spaces to bash function

时间:2017-04-09 23:37:54

标签: bash function arguments

I'm trying to pass a string to a function. The string contains multiple arguments and some of the arguments may begin with multiple spaces.

#!/bin/bash
test_function() {
    echo "arg1 is: '$1'"
    echo "arg2 is: '$2'"
    echo "arg3 is: '$3'"
}

a_string="one two \"  string with spaces in front\""
result=$(test_function $a_string)
echo "$result"

Here is the output actually produced:

arg1 is: 'one'
arg2 is: 'two'
arg3 is: '"'

Here is an example of the output I am trying to achieve:

arg1 is: 'one'
arg2 is: 'two'
arg3 is: '  string with spaces in front'

How can I store arguments containing spaces in a string like this to later be passed to a function?

Although it can be done with an array, I need to first convert the string into the array values.

2 个答案:

答案 0 :(得分:0)

With an array.

a_string=(one two "  string with spaces in front")
result=$(test_function "${a_string[@]}")

答案 1 :(得分:0)

bash -c 可能是您正在寻找的(或者甚至更好,eval,正如 John Kugelman 在下面指出的那样)。从手册页,

<块引用>

如果存在 -c 选项,则从 第一个非选项参数 command_string。如果有 是 command_string 之后的参数,第一个参数 被分配给 $0 并且任何剩余的参数是 分配给位置参数。分配给 $0 设置shell的名称,用于警告 和错误消息。

基本上bash -c "foo"foo 相同(加上一个子shell)。通过这种方式,我们可以轻松地将字符串作为参数插入。

这是在您的示例中:

#!/bin/bash
test_function() {
    echo "arg1 is: '$1'"
    echo "arg2 is: '$2'"
    echo "arg3 is: '$3'"
}

a_string="one two \"  string with spaces in front\""

export -f test_function
bash -c "test_function $a_string"

(在这个例子中 export 是必需的,因为它是一个定义的函数,但在其他情况下不会)。

输出:

arg1 is: 'one'
arg2 is: 'two'
arg3 is: '  string with spaces in front'