2

Here is what I am trying to do but I want to use python instead:

test=$(perl -e 'print "test"')
[webalert@localhost scripts]$ echo $test
test

Is there a python equivalent for perl -e ? Thx.

1 Answer 1

6
$ test=$(python -c "print 'hello'")
$ echo $test
hello

(as a side note...) If you want to preserve newlines, use quotes in the echo:

$ test=$(python -c "for i in range(3): print 'hello'")
$ echo $test
hello hello hello
$ echo "$test"
hello
hello
hello

One final tip:

Perl lends itself to one liners a bit better than Python does. I tend to do something like this rather than coerce python into being a language it is not:

$ test=$(python -c "
> import math
> import sys
> 
> for x in sys.argv[1:]:
>    print '2pi R of {}={}'.format(x,float(x)*2*math.pi)
> " 1 2.4 5 6.6)
$ echo "$test"
2pi R of 1=6.28318530718
2pi R of 2.4=15.0796447372
2pi R of 5=31.4159265359
2pi R of 6.6=41.4690230274
Sign up to request clarification or add additional context in comments.

4 Comments

Thx so much, works like a charm! Do you happen to have the man link for this? PS. I am just doing some simple date formatting, since all my scripts are in python I wanted to also use python in my shell script instead of perl. 1 dependenc is better than 2 :)
This is what I am doing: python -c 'import datetime; now=datetime.datetime.now();print "/{0:04d}/{1:02d}/{2:02d}".format(now.year, now.month, now.day)'
In perl its much cleaner, perl -e 'print strftime "%Y/%m/%d",localtime time-86400;'
I am the man! (i.e., I wrote this, and I do not know where you would find it exactly ;-) man python for the command line options. For what you describe, I would just use perl... Or use the python you have there. If I have a Bash questions, I usually go to tldp

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.