Home > Software design >  How can I permanently add a path to a path-related environment variable, when it may or may not be e
How can I permanently add a path to a path-related environment variable, when it may or may not be e

Time:01-13

I want to permanently add a path to $PYTHONPATH. According to this SO answer, adding

export PYTHONPATH="${PYTHONPATH}:/my/other/path"

to the .bashrc file should accomplish this on a Mac or GNU/Linux distro. However, on my system, $PYTHONPATH is empty, so after doing the export, if I echo $PYTHONPATH, it returns :/my/other/path - which is not a valid path because of the prefixed :. One way around this is to do

export PYTHONPATH="/my/other/path"

but that would clobber other paths if they do exist on different machines. How can I handle both cases?

CodePudding user response:

The if -z test will tell you if the variable is empty/unset. If so, don't use a colon, otherwise do use one.

if [ -z ${PYTHONPATH} ];
then
    export PYTHONPATH="/my/other/path"
else
    export PYTHONPATH="${PYTHONPATH}:/my/other/path"
fi

CodePudding user response:

You can put this in your .bashrc:

[ -z "${PYTHONPATH-}" ] && export PYTHONPATH="/my/other/path" || export PYTHONPATH="${PYTHONPATH}:/my/other/path"

which is the same as the previous answer.

  • Related