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

bash - pass script as argument of another script

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

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

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

./script1 (./script2 file1 file2) file3

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

如果这不可能,任何关于我如何规避该问题的提示都是合适的。

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

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

如果你想把script2作为参数传给script1在最后一个里面执行,只要把下面的代码放在里面script1 并像这样调用 script1

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

里面的代码script1:

 # 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:

"" "" ""
shift 3
another_command "$@" # do anything else with the rest of params (file3)