Bash – How to concatenate environment variable paths in a cleaner way in bash

bashpathshellunix-shell

In order to modify my paths (like LD_LIBRARY_PATH or PYTHONPATH), I first check is the variable exists. If so, I'm concatenating my old value with the new one (separated with a semicolon), else I'm settings my variable to the new value.

NEW_PATH='/path/to/new/path'  
if [ $LD_LIBRARY_PATH ]  
then  
    export LD_LIBRARY_PATH=$NEW_PATH:$LD_LIBRARY_PATH  
else  
    export LD_LIBRARY_PATH=$NEW_PATH  
fi  

It works, but it is a bit clumsy when you have lot of these in script to source : is there a clever trick to make this block a nice one liner ?

Thanks !

Best Answer

This syntax works :

export LD_LIBRARY_PATH=$NEW_PATH${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}