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

问题描述:

我有一个CLI,它会生成一个bash脚本。如何在不重定向到.sh文件的情况下立即评估它?Bash - 如何执行从不同脚本输出的脚本

例子是改变如下:

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

喜欢的东西:

~: toolWhichGeneratesScript | evaluate 
+0

非常感谢所有的快速答案。尴尬,我没有想到这一点!我应该回答谁的答案? –

+0

我会接受@thatotherguy提出的建议,因为它是最灵活的解决方案,除非您的'toolWhichGeneratesScript'可能会创建*非常*长的脚本,在这种情况下,其他脚本更安全。 – user1934428

你可以在命令传递与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 
      $0. 

与管道连接到shell不同,这使stdin免费供您与脚本运行的提示和程序进行交互。

外壳从标准输入读取它的脚本:

toolWhichGeneratesScript | sh 

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

请注意,您需要要知道哪个外壳要用;如果您的工具输出bash扩展名,那么您必须将其输入bash。另外,如果生成的脚本本身需要从标准输入中读取,则存在一些问题。

尝试这么做:toolWhichGeneratesScript | bash