1

In Linux and/or Mac OSX, what is the best way to automate moving an entry in the $PATH environment variable to the front of the value like this:

/foo/bar:/one/two/three:/opt/local/bin:/home/user/bin

Becomes

/home/user/bin:/foo/bar:/one/two/three:/opt/local/bin

Currently I'm using sed to accomplish this, but I'd like to know if there's a simpler solution.

1

I believe this is the simplest:

awk 'BEGIN{FS=OFS=":"}{print $4,$1,$2,$3}' <<< $PATH
0

Quickly, you could write:

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

If you have something like

PATH=/first:/second:/home/user/bin/subdir:/home/user/bin

then this is more robust:

tmp=":$PATH:"
tmp=$dir${tmp//:$dir:/:}
PATH=${tmp%:}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.