How to keep from duplicating path variable in csh

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!

Leave a Comment