【发布时间】:2015-12-18 23:45:58
【问题描述】:
我想在 shell 脚本中运行 Ruby/Python 单行程序,例如:
python 'print "hello world"'
或
ruby 'puts "hello world"'
或类似的东西,这样我就可以在其他地方快速输入。
【问题讨论】:
标签: python ruby bash perl shell
我想在 shell 脚本中运行 Ruby/Python 单行程序,例如:
python 'print "hello world"'
或
ruby 'puts "hello world"'
或类似的东西,这样我就可以在其他地方快速输入。
【问题讨论】:
标签: python ruby bash perl shell
从 2.05b 版开始,bash 可以使用 <<< 运算符从“此处的字符串”重定向标准输入 (stdin)。
$ python <<< 'print "hello world"'
hello world
$ ruby <<< 'puts "hello world"'
hello world
【讨论】:
这些命令中的每一个都有一个开关来执行作为参数传递的字符串。对于python,它是-c:
$ python -c 'print "hello world"'
hello world
对于 ruby,它是 -e:
$ ruby -e 'puts "hello world"'
hello world
顺便说一句,python --help、ruby --help 的输出或在man 页面中查找任一程序都会为您提供答案。
【讨论】:
使用解释器的参数告诉它下一个参数是要运行的代码。
python -c 'print "hello world"'
【讨论】:
对于红宝石:
ruby -e 'puts "Hello world"'
【讨论】:
在 Perl 中,从命令行:
perl -e 'print "Hello World\n";'
或者在 bash 脚本中:
#!/bin/bash
perl -e 'print "Hello World\n";'
【讨论】:
perl -E 'say "Hello World"'。你根本不需要;。实际上 OP 并没有要求换行。
如果您的意思是在管道中使用一层 perl/awk/python,它就像大多数其他 Unix 实用程序一样:
$ python -c 'print "hello"' | tr "[a-z]" "[A-Z]"
HELLO
$ ruby -e 'puts "hello"' | tr "[a-z]" "[A-Z]"
HELLO
$ python -c 'print "GREETINGS"' | perl -lpe 's/([EI])/lc($1)/ge'
GReeTiNGS
【讨论】:
您不需要 Perl、Python 或 Ruby 将固定字符串通过管道传输到另一个应用程序。可以使用echo 程序。
$ echo 'foo' | cat
foo
更多信息请参见explainshell.com。
【讨论】: