bash - 将脚本作为另一个脚本的参数传递

时间:2015-01-04 20:40:54

标签: bash

我无法在SO上找到类似的问题。

如何正确地将bash脚本作为参数传递给另一个bash脚本。

例如,假设我有两个脚本可以接受多个参数,我想传递一个脚本作为另一个脚本的参数。类似的东西:

./script1 (./script2 file1 file2) file3

在上面的示例中,script2将file1和file2合并在一起,然后回显一个新文件,但这与问题无关。我只想知道如何将script2作为参数传递,即正确的语法。

如果无法做到这一点,任何关于我如何规避问题的提示都是合适的。

2 个答案:

答案 0 :(得分:5)

如果要将评估script2的结果作为参数传递,请使用$()。请记住,你必须引用它。

./script1 "$(./script2 file1 file2)" file3

答案 1 :(得分:3)

如果您想将 script2 作为参数传递给 script1 以在最后一个内执行它,只需将以下代码放在 script1 中并按照以下方式调用 script1

./script1 "./script2 file1 file2" file3  # file4 file5

script1 中的代码:

$1 # here you're executing ./script2 file1 file2
shift
another_command "$@" # do anything else with the rest of params (file3)

或者如果您知道 script2 的参数数量并且它已修复,您也可以按以下方式执行:

./script1 ./script2 file1 file2 file3  # file4 file5

script1 中的代码:

"$1" "$2" "$3"
shift 3
another_command "$@" # do anything else with the rest of params (file3)
相关问题