简体   繁体   English

来自Bash的Perl / Python / Ruby运行行

[英]Run line of Perl/Python/Ruby from Bash

I want to run a Ruby/Python one-liner in a shell script, like: 我想在shell脚本中运行Ruby / Python单行代码,例如:

python 'print "hello world"'

or 要么

ruby 'puts "hello world"'

or something like that so I can quickly pipe the input elsewhere. 或类似的东西,以便我可以快速将输入传递到其他地方。

Since version 2.05b, bash can redirect standard input (stdin) from a "here string" using the <<< operator. 从2.05b版本开始,bash可以使用<<<运算符从“此处字符串”重定向标准输入(stdin)。

$ python <<< 'print "hello world"'
hello world
$ ruby <<< 'puts "hello world"'
hello world

Each of these commands has a switch to execute a string passed as an argument. 这些命令中的每一个都有一个开关,以执行作为参数传递的字符串。 For python, it's -c : 对于python,它是-c

$ python -c 'print "hello world"'
hello world

For ruby, it's -e : 对于红宝石,它是-e

$ ruby -e 'puts "hello world"'
hello world

By the way, the output of python --help , ruby --help or looking in the man page for either program would give you the answer. 顺便说一句, python --helpruby --help的输出或在man页中查找任一程序都会为您提供答案。

使用解释器的参数,告诉它下一个参数是要运行的代码。

python -c 'print "hello world"'

对于Ruby:

ruby -e 'puts "Hello world"'

If you mean using a one liner of perl/awk/python in a pipe, it is just like most other Unix utilities: 如果您要在管道中使用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

In Perl, from command line: 在Perl中,从命令行:

perl -e 'print "Hello World\n";'

Or inside bash script: 或在bash脚本中:

#!/bin/bash

perl -e 'print "Hello World\n";'

You need neither Perl, Python or Ruby to pipe a fixed string to another application. 您不需要Perl,Python或Ruby即可将固定的字符串传递到另一个应用程序。 The echo program can be used for that. echo程序可用echo

$ echo 'foo' | cat
foo

See explainshell.com for more infos. 有关更多信息,请参见explainshell.com

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM