Append to an environment variable without overwriting values from .env file

5,729

What you most likely want to do is export the variables you are interested in. The following will make the variable available to the current shell and any sub-processes it creates:

export PYTHONPATH=$PYTHONPATH:/Users/James/project

Here a process that uses PYTHONPATH will first search the existing path for its target and if not found, try the /Users/James/project. If you wanted to overide some existing path, you could add the new path first:

export PYTHONPATH=/Users/James/project:$PYTHONPATH

In either case, other shells will not see the variable (and obviously closing the shell will make the variable unaccessible).

Share:
5,729

Related videos on Youtube

noɥʇʎԀʎzɐɹƆ
Author by

noɥʇʎԀʎzɐɹƆ

CrazyPython is an expert in disliking profiles written in the third person. With over ten years of experience at breathing... You can contact me at my email, jamtlu+so (at) gmail dot com.

Updated on September 18, 2022

Comments

  • noɥʇʎԀʎzɐɹƆ
    noɥʇʎԀʎzɐɹƆ over 1 year

    Assuming the .env file is loaded before execution, how can you append to it without overriding it?

    DEBUG=True
    FOO=BAR
    PYTHONPATH="/Users/James/project/"
    

    The above file would (?) override it, and that would be bad. I could put it in .bash_profile or .profile, but that's not consistent with what I have now, and I only want to set it for the current virtualenv too.

    I don't think this makes any difference, but I'm using Mac OS X (the tutorial I was using was multi-platform)

    • Jonathan Roberts
      Jonathan Roberts almost 9 years
      What are you trying to do? You want to add a couple environment variables temporarily? It sounds like you just want to export DEBUG=True. This will set the DEBUG variable only for the current shell and it's children.
    • noɥʇʎԀʎzɐɹƆ
      noɥʇʎԀʎzɐɹƆ almost 9 years
      @user1794469 Is that possible in the .env file? I want to append to PYTHONPATH.
    • Jonathan Roberts
      Jonathan Roberts almost 9 years
      It shoudl, you just add the current: export PYTHONPATH=$PYTHONPATH:/Users/James/project or export PYTHONPATH=/Users/James/project:$PYTHONPATH depending on which path you want search first.