0

I want to run a Ruby/Python one-liner in a shell script, like:

python 'print "hello world"'

or

ruby 'puts "hello world"'

or something like that so I can quickly pipe the input elsewhere.

7 Answers 7

6

Since version 2.05b, bash can redirect standard input (stdin) from a "here string" using the <<< operator.

$ python <<< 'print "hello world"'
hello world
$ ruby <<< 'puts "hello world"'
hello world
Sign up to request clarification or add additional context in comments.

1 Comment

One of the only answers with a unique answer. Thanks
5

Each of these commands has a switch to execute a string passed as an argument. For python, it's -c:

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

For ruby, it's -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.

Comments

2

Use the argument to the interpreter that tells it that the next argument is code to be run.

python -c 'print "hello world"'

Comments

1

For Ruby:

ruby -e 'puts "Hello world"'

Comments

1

In Perl, from command line:

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

Or inside bash script:

#!/bin/bash

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

1 Comment

You can also save two characters and go perl -E 'say "Hello World"'. You don't need the ; at all. Actually OP was not asking for a line break though.
1

If you mean using a one liner of perl/awk/python in a pipe, it is just like most other Unix utilities:

$ 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

5 Comments

Seems kinda harsh to vote this down given the votes on the other answers here.
Printing from Python to pipe to Perl to use regex! :-)
@sawa: what are you saying? Posts should be judged not just on what they say but what they used to say???
@thewolf [W]hat are you saying? Votes should foresee the future edit[?]
I suppose not being one who down votes often I think it does make sense to change the vote if the original reason is no longer there. I personally only down vote if a) the answer is wrong and b) someone does not change it if given a chance.
1

You need neither Perl, Python or Ruby to pipe a fixed string to another application. The echo program can be used for that.

$ echo 'foo' | cat
foo

See explainshell.com for more infos.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.