1

I have a script:

x.sh:

#!/bin/bash
echo nir

config.sh:

#!/bin/bash
x=$(/home/nir/x.sh)

script.py:

#!/usr/bin/env python3
#execute config.sh and read x into y
print(y)

terminal:

$ ] ./x.sh
nir
$ ] . ./config.sh
$ ] echo $x
nir
$ ] ./script.py
nir

I want to use config.sh in a python script to execute it and then read the value in x. Not sure how to do it.

3
  • echo nir will not echo nir variable. I think you may have wanted to use echo $nir Commented Dec 28, 2022 at 7:52
  • To make it clear: In your example, you want to receive the string nir inside your Python program? Commented Dec 28, 2022 at 7:55
  • added example to make it clearer. Commented Dec 28, 2022 at 8:24

1 Answer 1

1

Since config.sh is not showing output, you need another command for showing the value of x. Any shell variable set in a subprocess is lost when the subprocess is finished, so you can not use two calls to subprocess.
The same problem is valid for config.sh: the variables are lost when the script is finished. You need to source the file with a . for the variable to be remembered in the subprocess environment. Before finishing the subcommand, you must echo the value.
All steps together:

#!/usr/bin/env python3
import subprocess

cmd = '''
. /home/nir/config.sh
echo "$x"
'''

# returns output as byte string
returned_output = subprocess.check_output(cmd, shell=True)

# using decode() function to convert byte string to string
y=returned_output.decode("utf-8")
print(y)
Sign up to request clarification or add additional context in comments.

3 Comments

work great! one question - how can I make the path of config.sh relative to the location of script.py? (which is the script you actual wrote)
Try . ./config.sh (first dot for source, second for relative to current dir).
found it os.path.join(os.path.dirname(__file__),....

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.