【问题标题】:How to split contained words string to to function parameters in BASH?如何将包含的单词字符串拆分为 BASH 中的函数参数?
【发布时间】:2015-08-21 05:42:11
【问题描述】:

示例代码

input="cp directory_a directory_b" # obtaining value from keyboard

eval_input $input

我希望$input可以在eval_input函数中拆分成$0$1$2。到目前为止我都是用这个方法存档的

eval_input $(echo $input)

但我认为也许还有更好的方法。

注意这里的$input,实际上它的值是从不是我自己分配的用户那里获得的。

【问题讨论】:

    标签: bash parameters arguments


    【解决方案1】:

    在 shell 中拆分字符串会导致许多难题。最好的解决方案是不创建字符串。使用数组:

    input=(cp directory_a directory_b)
    eval_input "${input[@]}"
    

    这提供了cpdirectory_adirectory_b 作为eval_input 的参数,eval_input 可以将其引用为$1,$2, and$3`。

    即使某些命令的参数包含空格或其他困难字符,这种方法也可以工作。例如,以下将很好地工作:

    input=(cp "directory a" "directory b")
    

    尝试使用字符串而不是数组来做到这一点将非常困难。

    使用用户提供的字符串

    您可以使用read 命令将用户提供的输入分解为单个参数:

    $ input="cp directory_a directory_b"
    $ read -a array <<<"$input"
    

    您可以通过检查declare -p 的输出来验证上述是否成功:

    $ declare -p array
    declare -a array='([0]="cp" [1]="directory_a" [2]="directory_b")'
    

    您可以访问array 的各个元素,如下所示:

    $ echo "${array[0]}"
    cp
    $ echo "${array[1]}"
    directory_a
    

    【讨论】:

    • 请检查我刚刚添加到问题中的注释。
    【解决方案2】:

    您可以使用set --设置位置参数:

    ( input="cp directory_a directory_b"; set -- $input; echo "[$1] [$2] [$3]"; )
    

    输出:

    [cp] [directory_a] [directory_b]
    

    PS:使用(...) 来避免弄乱当前的 shell,并在子 shell 中执行此操作。

    【讨论】:

    • 这种方法具有 POSIX 兼容性的优点。 +1
    猜你喜欢
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 2022-07-06
    • 2012-07-29
    • 2022-01-08
    相关资源
    最近更新 更多