如何从 bash shell stdin 执行脚本代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18483097/
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
How to execute script code from bash shell stdin?
提问by CatWin
I want to execute script code like python from bash standard input, because I don't want to write a script to file first. And how to do ? If I want to run python code from bash standard input like:
我想从bash标准输入执行像python这样的脚本代码,因为我不想先将脚本写入文件。怎么办?如果我想从 bash 标准输入运行 python 代码,例如:
#!/usr/bin/env python
print 'hello world'
$cat mycode.py | bash -s
$cat mycode.py | bash -s
But it doesn't work. An error showed:
但它不起作用。一个错误显示:
Warning: unknown mime-type for "hello world" -- using "application/octet-stream"
Error: no such file "hello world"
错误:没有这样的文件“hello world”
回答by Michael Kazarian
But it doesn't work.An error showed: Warning: unknown mime-type for "hello world" -- using "application/octet-stream" Error: no such file "hello world"
但它不起作用。显示错误:警告:“hello world”的未知 mime-type -- 使用“application/octet-stream”错误:没有这样的文件“hello world”
Of cource, bash don't know command hello world
and system suggest install something. Below can work
当然,bash 不知道命令hello world
和系统建议安装一些东西。下面可以工作
python -c 'print "ls -l"' | bash
回答by Michael Kazarian
As variant you can make similar to this scenario:
作为变体,您可以类似于此场景:
$ cat test.py
#!/usr/bin/python
import sys
if sys.version_info[0] == 2:
sys.stdout.write("ls -l")
$ python test.py | bash
итого 4
-rw-rw-r-- 1 miha miha 91 авг. 28 12:21 test.py
$ chmod +x test.py
$ ./test.py | bash
итого 4
-rwxrwxr-x 1 miha miha 91 авг. 28 12:21 test.py