Home > Software engineering >  read variable value from bash executable
read variable value from bash executable

Time:12-29

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.

CodePudding user response:

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)
  • Related