Preventing duplicate entried in PATH (.cshrc)

cshpath

I need to prepend directories to the path variable in my .cshrc file and I want to make sure that the entries are not repeated when compared to existing directories in the path variable. Can someone advise suitable commands for that? The path on my machine is : separated, not space separated.

Best Answer

If on Linux, I suppose your csh is tcsh. Then you should be able to do:

set -f path=("/new/entry" $path:q)

In csh, tcsh and zsh, the $path special array variable is tied to the $PATH scalar environment variable in that the elements of the $path array are constructed by splitting the $PATH variable on the colon character. Any modification of either $path or $PATH is automatically reflected into the other variable.

-f above is to retain only the first entry. $path:q is the elements of $path, quoted, that is preventing word splitting. So the syntax above prepends the /new/entry or moves it to the front if it was already there.

Why would you be using csh though?


Note: the quotes above are necessary. Or more precisely, all the characters in /new/entry need to be quoted one way or another.

set -f path=('/new/'\e"ntry" $path:q)

is OK.

set -f path=(/'new/entry' $path:q)

is not. You can always do it in two stages though:

set path=(/new/entry $path:q)
set -f path=($path:q)

(one of the reasons you may want to stay away from csh)

Related Question