How to keep from duplicating path variable in csh

dr_pepper picture dr_pepper · Sep 25, 2008 · Viewed 9k times · Source

It is typical to have something like this in your cshrc file for setting the path:

set path = ( . $otherpath $path )

but, the path gets duplicated when you source your cshrc file multiple times, how do you prevent the duplication?

EDIT: This is one unclean way of doing it:

set localpaths = ( . $otherpaths )
echo ${path} | egrep -i "$localpaths" >& /dev/null
if ($status != 0) then
    set path = ( . $otherpaths $path )
endif

Answer

MestreLion picture MestreLion · Feb 19, 2011

Im surprised no one used the tr ":" "\n" | grep -x techique to search if a given folder already exists in $PATH. Any reason not to?

In 1 line:

if ! $(echo "$PATH" | tr ":" "\n" | grep -qx "$dir") ; then PATH=$PATH:$dir ; fi

Here is a function ive made myself to add several folders at once to $PATH (use "aaa:bbb:ccc" notation as argument), checking each one for duplicates before adding:

append_path()
{
    local SAVED_IFS="$IFS"
    local dir
    IFS=:
    for dir in $1 ; do
        if ! $( echo "$PATH" | tr ":" "\n" | grep -qx "$dir" ) ; then
            PATH=$PATH:$dir
        fi
    done
    IFS="$SAVED_IFS"
}

It can be called in a script like this:

append_path "/test:$HOME/bin:/example/my dir/space is not an issue"

It has the following advantages:

  • No bashisms or any shell-specific syntax. It run perfectly with !#/bin/sh (ive tested with dash)
  • Multiple folders can be added at once
  • No sorting, preserves folder order
  • Deals perfectly with spaces in folder names
  • A single test works no matter if $folder is at begginning, end, middle, or is the only folder in $PATH (thus avoiding testing x:*, *:x, :x:, x, as many of the solutions here implicitly do)
  • Works (and preserve) if $PATH begins or ends with ":", or has "::" in it (meaning current folder)
  • No awk or sed needed.
  • EPA friendly ;) Original IFS value is preserved, and all other variables are local to the function scope.

Hope that helps!