简体   繁体   English

将字符串作为带空格的参数传递给 bash 函数

[英]pass string as arguments with spaces to bash function

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.虽然可以用数组来完成,但我需要先将字符串转换为数组值。

With an array.用数组。

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

bash -c may be what you're looking for (or perhaps even better, eval , as John Kugelman points out below). bash -c可能是您正在寻找的(或者甚至更好, eval ,正如 John Kugelman 在下面指出的那样)。 From the man page,从手册页,

If the -c option is present, then commands are read from the first non-option argument command_string.如果存在 -c 选项,则从第一个非选项参数 command_string 中读取命令。 If there are arguments after the command_string, the first argument is assigned to $0 and any remaining arguments are assigned to the positional parameters.如果在 command_string 之后有参数,则第一个参数被分配给 $0,任何剩余的参数都分配给位置参数。 The assignment to $0 sets the name of the shell, which is used in warning and error messages.对 $0 的赋值设置了 shell 的名称,该名称用于警告和错误消息。

Basically bash -c "foo" is the same (plus a subshell) as foo .基本上bash -c "foo"是相同的(加上一个子shell),为foo In this way we can easily insert our string as arguments.通过这种方式,我们可以轻松地将字符串作为参数插入。

Here it is in your example:这是在您的示例中:

#!/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"

(The export is necessary in this example because it's a defined function, but wouldn't be in other cases). (在这个例子中export是必要的,因为它是一个定义的函数,但在其他情况下不会)。

Output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM