Bash - 如何执行从不同脚本输出的脚本

Bash - How to execute a script which is output from a different script

我有一个生成 bash 脚本的 CLI。如何在不重定向到 .sh 文件的情况下立即对其进行评估?

示例是更改以下内容:

~: toolWhichGeneratesScript > tmp.sh
~: chmod +x tmp.sh
~: ./tmp.sh

类似于:

~: toolWhichGeneratesScript | evaluate

您可以使用 bash -c(或 sh -c)将命令传递给 运行:

bash -c "$(toolWhichGeneratesScript)"
   -c        If the -c option is present, then  commands
             are read from the first non-option argument
             command_string.   If  there  are  arguments
             after the command_string, they are assigned
             to the positional parameters, starting with
             [=11=].

与 shell 的管道不同,这让您可以自由地使用 stdin 与提示进行交互并对脚本 运行s 进行编程。

shell 从标准输入读取脚本:

toolWhichGeneratesScript | sh

(事实上,交互式 shell 做同样的事情;它的标准输入恰好是一个终端。)

请注意,您需要知道要使用哪个 shell;如果您的工具输出 bash 扩展名,那么您必须将其通过管道传输到 bash。另外,如果生成的脚本本身需要从标准输入中读取,你就有一点问题了。

尝试这样做:toolWhichGeneratesScript | bash