-1

Currently trying to pass a parameter from my python script to a bash script I created. How can I can get user input from my python script to my bash script?

This is the code for my python script 'passingParameters.py' which I used to try and send a variable (loop) to my bash script. I have tested this python script (after I adjusted the code) by sending the output to another python script which I used to read the input.

loop = str(sys.argv[1])
subprocess.check_call( ["./test.sh", loop], shell=True)

This is the code for my bash script 'test.sh'. I have tested this script by itself to confirm that it does receive user input when I just call the bash script from the command line.

echo "This number was sent from the passParameters.py script: " $1
5
  • 1
    Pretty related: How do I pass a Python Variable to Bash? Commented Aug 5, 2014 at 13:44
  • 1
    The code should work. Do you get an error? Or why do you think the parameter isn't passed? Commented Aug 5, 2014 at 13:57
  • @AaronDigulla no error, just the value I input into the command line doesn't show up Commented Aug 5, 2014 at 14:27
  • @MOS182 See my comment to crono's answer. Commented Aug 5, 2014 at 14:32
  • Possible duplicate of How to pass variables from python script to bash script Commented Sep 23, 2018 at 0:34

1 Answer 1

4

If you use shell=True then the executable is /bin/sh, which then calls test.sh but never sees the loop variable. You can either set shell=False and add the #!/bin/sh to the shell script,

#! /bin/sh
echo "This number was sent from the passParameters.py script: " $1

and

subprocess.check_call( ["./test.sh", loop], shell=False)

or pass the variable as a string:

subprocess.check_call( ["./test.sh %s" % loop], shell=True)

shell=True is not recommended anyway.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 It's not well documented, but combining your list of arguments with shell=True will result in the following command: sh -c ./test.sh <loop>. This will still run ./test.sh, but the argument loop is passed to sh as $0 rather than to ./test.sh as $1.
Thanks for your help! This first suggestion works fine. I tried the second suggestion with shell=True and it didn't work, says invalid syntax for the % beside loop.
@chepner that's what I thought might have explained why it wasn't displayed so instead of having $1 in the bash script, I tried $0 and it still didn't print out anything.
When you pass the variable as a string, the list is just superfluous. subprocess.check_call("./test.sh %s" % loop, shell=True). But as you note, you really want to avoid shell=True if you can. See also Actual meaning of shell=True in subprocess

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.