1

I see two different ways of adding path in Linux. For example,

export PATH=/usr/local/cuda/bin${PATH:+:${PATH}}
export PATH=/usr/local/cuda/bin:$PATH

While I am clearly aware of the second way, what is first way doing? What are the advantages over the second?

SKPS
  • 5,433
  • 5
  • 29
  • 63
  • `${var:+X}` expands to `X` when `var` is non-empty, and to nothing otherwise; in your case it ensures that you won't end up with a PATH that ends with `:` – Fravadona Aug 17 '23 at 16:57
  • Suppose if PATH is empty, is there any danger in using the second way? – SKPS Aug 17 '23 at 17:05
  • I'm not sure; an empty component in `$PATH` might get interpreted as a `.` in some shells? – Fravadona Aug 17 '23 at 17:19
  • 1
    @Fravadona: I just made a quick test with zsh and bash (on macos, but the OS should not matter for this question), and indeed, this seems to be the interpretation. – user1934428 Aug 18 '23 at 07:39

1 Answers1

3

When PATH is empty, then:

export PATH=/usr/local/cuda/bin:$PATH

Results in

PATH=/usr/local/cuda/bin:

The empty :<nothing> is indicates current working directory, reference https://www.gnu.org/software/bash/manual/bash.html#index-PATH . The code added current working directory and cuda to path. This is not intended.

Instead, you want to add a : only if PATH is not empty. This is what ${PATH:+:${PATH}} achieves.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111