运行从标准输入管道传输的脚本(Linux/Shell 脚本)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9966111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:32:15  来源:igfitidea点击:

Run a script piped from stdin (Linux/Shell Scripting)

linuxshellscriptingcommand-line

提问by Switch

Suppose I have a script: my_script.sh

假设我有一个脚本:my_script.sh

Instead of doing

而不是做

./my_script.sh

I want to do something like:

我想做类似的事情:

cat my_script.sh | <some command here>

such that the script executes. Is this possible?

以便脚本执行。这可能吗?

The use case is if the script I want to execute is the output of a wget or s3cat, etc. Right now I save it to a temporary file, change it to executable, and then run it. Is there a way to do it directly?

用例是如果我要执行的脚本是 wget 或 s3cat 等的输出。现在我将它保存到一个临时文件中,将其更改为可执行文件,然后运行它。有没有办法直接做到这一点?

采纳答案by Mat

Just pipe it to your favorite shell, for example:

只需将其通过管道传输到您最喜欢的 shell,例如:

$ cat my_script.sh
set -x
echo hello
$ cat my_script.sh | sh
+ echo hello
hello

(The set -xmakes the shell print out each statement it is about to run before it runs it, handy for debugging, but it has nothing to do with your issue specifically - just there for demo purposes.)

(这set -x使得 shell 在运行之前打印出它将要运行的每个语句,便于调试,但它与您的问题无关 - 仅用于演示目的。)

回答by Mihai

You could use stdin from pipe:

您可以使用管道中的标准输入:

cat my_script.sh | xargs -i <some_command> {}

or:

或者:

cat my_script.sh | bash -

or (just from stdin):

或(仅来自标准输入):

bash < my_script.sh

回答by l0b0

RVM recommends this method to run their installer:

RVM 推荐这种方法来运行他们的安装程序

bash -s stable < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer)