Skip to content

Instantly share code, notes, and snippets.

@chiangbing
Last active December 18, 2015 11:59
Show Gist options
  • Save chiangbing/5779195 to your computer and use it in GitHub Desktop.
Save chiangbing/5779195 to your computer and use it in GitHub Desktop.
Read variables in bash script by sourcing the file and echoing the variable.
def get_var(srcfile, *variables):
"""Get variables' values from bash shell source file.
Return a dictionary that maps from variable name to its value.
"""
cmd = ". " + srcfile + ";"
for var in variables:
cmd += "echo ${" + var + "};"
proc = subprocess.Popen([cmd], stdout=subprocess.PIPE, shell=True)
output = proc.communicate()[0]
proc.stdout.close()
if output is None:
return {}
else:
values = output.split("\n")
return dict(zip(variables, values))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment