purpleminion
purpleminion

Reputation: 87

How to pass arguments from a bash script to a function that uses python?

#!/bin/bash

#=================
function func1 {
#=================

echo "I have chickens"

func2 100

}
#================
function func2 {
#================

number=$1

python << END

print "I have", number, "chickens"

END
}

func1

In bash I want to pass func2 an argument. In func2 I want to print the argument using python.

Desired output:

I have chickens

I have 100 chickens

Upvotes: 0

Views: 55

Answers (1)

Carsten
Carsten

Reputation: 18446

Regular bash string variable substitution works:

$ export n=3
$ python << END
> print "I have ${n} chickens"
> END

Output:

I have 3 chickens

Because of this, you have to be very careful if you wish to continue your (rather unusual) approach. A much more common way would be to have the Bash and Python programs in separate files and run the Python script from the Bash script with some command line arguments. You can then access them from Python as sys.argv, or, if you want to do anything more sophisticated, argparse.

Upvotes: 4

Related Questions