【问题标题】:pass string as arguments with spaces to bash function将字符串作为带空格的参数传递给 bash 函数
【发布时间】:2017-09-04 21:37:04
【问题描述】:

我正在尝试将字符串传递给函数。该字符串包含多个参数,并且某些参数可能以多个空格开头。

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

这是实际产生的输出:

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

这是我想要实现的输出示例:

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

如何将包含空格的参数存储在这样的字符串中,以便稍后传递给函数?

虽然可以用数组来完成,但我需要先将字符串转换成数组值。

【问题讨论】:

    标签: bash function arguments


    【解决方案1】:

    With an array.

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

    【讨论】:

    • 问题是我需要先将字符串转换为数组值。 an_array=("$a_string") 这是怎么做到的?
    • 你没有。您使用数组开头。
    • 在实际应用中说起来容易做起来难。它通过多个函数传递并在此过程中进行操作。
    • 它需要更多的工作,但是您可以将数组的名称作为参数传递,并使用间接访问。在某些情况下,简单地将元素作为位置参数传递(使用$@)效果很好,它不是一个数组,但工作方式类似。
    【解决方案2】:

    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'
    

    【讨论】:

    • eval 更简单,并且在当前shell而不是子shell中执行。不过,我不推荐它,也不推荐bash -c。 Ignacio 建议使用数组是可行的方法。永远不要在这样的字符串中存储多个单词。试图解开损坏的数据是没有意义的;只是避免首先破坏它。
    猜你喜欢
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 2011-05-27
    • 2016-04-08
    • 2012-07-26
    相关资源
    最近更新 更多