Search code examples
pythonbashreturn-valueprogram-entry-point

How to return a value from Python script as a Bash variable?


This is a summary of my code:

# import whatever

def createFolder():
    #someCode
    var1=Gdrive.createFolder(name)
    return var1 

def main():
    #someCode
    var2=createFolder()
    return var2

if __name__ == "__main__":
    print main()

One way in which I managed to return a value to a bash variable was printing what was returned from main(). Another way is just printing the variable in any place of the script.

Is there any way to return it in a more pythonic way?

The script is called this way:

folder=$(python create_folder.py "string_as_arg")

Solution

  • If you were working in bash then you could simply do:

    export var="value"
    

    However, there is no such equivalent in Python. If you try to use os.environ those values will persist for the rest of the process and will not modify anything after the program finishes. Your best bet is to do exactly what you are already doing.