Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One liner to set environment variable if doesn't exist, else append

Tags:

bash

shell

unix

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.

like image 741
Cheetah Avatar asked Apr 30 '13 09:04

Cheetah


People also ask

How do I add to an environment variable?

On Windows 7, just type "system" in the META-Prompt and you'll see an entry "Edit the System Environment Variables". From there, click "Environment variables". There, you can either edit the system variable PATH (bottom list) or add/edit a new PATH variable to the user environment variables.

How do you check if Python is added to environment variable exists?

getenv() method in Python returns the value of the environment variable key if it exists otherwise returns the default value. default (optional) : string denoting the default value in case key does not exists.

What does || mean in shell script?

Show activity on this post. The || is an “or” comparison operator. The : is a null operator which does… Nothing. Well, it does return a successful exit status…


2 Answers

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

PATH=${PATH:+$PATH:}/path/to/bin
like image 66
spbnick Avatar answered Oct 21 '22 02:10

spbnick


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 ":"
like image 37
Michael Burr Avatar answered Oct 21 '22 02:10

Michael Burr