xis
xis

Reputation: 24850

How to understand "${PATH:+:${PATH}}" in bash?

I am seeing the following code in a bash script:

export PATH=/opt/rh/rh-python38/root/usr/local/bin:/opt/rh/rh-python38/root/usr/bin${PATH:+:${PATH}}

I do not understand the last part, where ${PATH:+:${PATH}} is manipulated.

Upvotes: 2

Views: 388

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52112

It's to append : and $PATH, but only if $PATH is non-empty; otherwise, nothing gets added.

The syntax for the expansion is ${parameter:+word}, and it stands for

If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.

In your example, word is :$PATH.

There is a subtlety around ${parameter:+word} vs. ${parameter+word}, where the former substitutes nothing if parameter is unset or null, and the latter substitutes nothing only if parameter is unset (but could be empty).

Upvotes: 4

Related Questions