(TIL) Bash: Append to variable without creating leading colon if unset

less than 1 minute read

Say you need to append a directory to PATH, but only add a leading : if PATH is already set. The standard

export PATH=${PATH}:/home/user/bin

won’t work correctly if PATH is not set – you’ll get :/home/user/bin instead of /home/user/bin.

Instead you the ${:+} expansion operator:

export PATH=${PATH:+${PATH}:}/home/user/bin

The first braces expand to $PATH and the colon iff PATH is set already, otherwise to nothing.

Via unix.stackexchange.com.

Tags: ,

Categories:

Updated:

Comments