22

I am using bash.

There is an environment variable that I want to either append if it is already set like:

PATH=$PATH":/path/to/bin"

Or if it doesn't already exist I want to simply set it:

PATH="/path/to/bin"

Is there a one line statement to do this?

Obviously the PATH environment variable is pretty much always set but it was easiest to write this question with.

3 Answers 3

26

A little improvement on Michael Burr's answer. This works with set -u (set -o nounset) as well:

PATH=${PATH:+$PATH:}/path/to/bin 
Sign up to request clarification or add additional context in comments.

1 Comment

What is the csh equivalent to this?
24
PATH=${PATH}${PATH:+:}/path/to/bin 
  • ${PATH} evaluates to nothing if PATH is not set/empty, otherwise it evaluates to the current path
  • ${PATH:+:} evaluates to nothing if PATH is not set, otherwise it evaluates to ":"

3 Comments

This syntax is known as Shell Parameter Expansion and full documentation on this feature can be found in the man page.
What is the csh equivalent to this with setenv?
How do you do the same if both are variables, which may or may not exists? Basically append 2 variables if they exists. Is it possible to get the below as one-liner? if [[ -n ${PATH} ]]; then PATH="${PATH}${BIN_PATH:+,}${BIN_PATH}"; else PATH="${BIN_PATH}"; fi
3

The answers from Michael Burr and user spbnick are already excellent and illustrate the principle. I just want to add two more details:

In their versions, the new path is added to the end of PATH. This is what the OP asked, but it is a less common practice. Adding to the end means that the commands will only be picked if no other commands match from earlier paths. More commonly, users will add to the front to path. This is not what the OP asked, but for other users coming here it may be closer to what they expect. Since the syntax is different I'm highlighting it here.

Also, in the previous versions, the PATH is not quoted. While its unlikely on most Un*x-like operating systems to have spaces in PATH, it is still better practice to always quote.

My slightly improved version, for most typical use cases, is

PATH="/path/to/bin${PATH:+:$PATH}" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.