【问题标题】:bash - pass script as argument of another scriptbash - 将脚本作为另一个脚本的参数传递
【发布时间】:2015-01-04 20:40:53
【问题描述】:

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

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

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

./script1 (./script2 file1 file2) file3

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

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

【问题讨论】:

  • 你打算如何使用script2,一旦你将它“传递”给script1?
  • 目前,我不太确定,我使用的script1 只是迭代了参数的所有内容。但是,我只是想弄清楚如何将脚本作为参数传递,因为它不适合我。
  • 我仍然不清楚您的目标是什么,或者将脚本作为参数传递的真正含义。参数只是字符串。大概你想在某个时候运行script2 传递文件名file1 和file2。传递这个动作的结果就足够了吗?
  • 我的目标基本上是@Cameron Martin 的回答。
  • 那么,你为什么接受另一个答案?

标签: bash


【解决方案1】:

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

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

【讨论】:

  • 其中评估表示将标​​准输出作为单个参数捕获。
【解决方案2】:

如果您想将 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)

【讨论】:

    猜你喜欢
    • 2022-12-08
    • 2023-04-03
    • 1970-01-01
    • 2014-12-26
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多