How to keep from duplicating path variable in csh

前端 未结 12 748
我在风中等你
我在风中等你 2020-11-27 05:19

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

set path = ( . $otherpath $path )

but, the path gets dup

相关标签:
12条回答
  • Here is a long one-liner without sorting:
    set path = ( echo $path | tr ' ' '\n' | perl -e 'while (<>) { print $_ unless $s{$_}++; }' | tr '\n' ' ')

    0 讨论(0)
  • 2020-11-27 05:53

    ok, not in csh, but this is how I append $HOME/bin to my path in bash...

    case $PATH in
        *:$HOME/bin | *:$HOME/bin:* ) ;;
        *) export PATH=$PATH:$HOME/bin
    esac
    

    season to taste...

    0 讨论(0)
  • 2020-11-27 05:53

    Well, if you don't care what order your paths are in, you could do something like:

    set path=(`echo $path | tr ' ' '\n' | sort | uniq | tr '\n' ' '`)
    

    That will sort your paths and remove any extra paths that are the same. If you have . in your path, you may want to remove it with a grep -v and re-add it at the end.

    0 讨论(0)
  • 2020-11-27 05:56

    dr_peper,

    I usually prefer to stick to scripting capabilities of the shell I am living in. Makes it more portable. So, I liked your solution using csh scripting. I just extended it to work on per dir in the localdirs to make it work for myself.

    foreach dir ( $localdirs )
        echo ${path} | egrep -i "$dir" >& /dev/null
        if ($status != 0) then
            set path = ( $dir $path )
        endif
    end
    
    0 讨论(0)
  • 2020-11-27 05:56

    When setting path (lowercase, the csh variable) rather than PATH (the environment variable) in csh, you can use set -f and set -l, which will only keep one occurrence of each list element (preferring to keep either the first or last, respectively).

    https://nature.berkeley.edu/~casterln/tcsh/Builtin_commands.html#set

    So something like this

    cat foo.csh # or .tcshrc or whatever: set -f path = (/bin /usr/bin . ) # initial value set -f path = ($path /mycode /hercode /usr/bin ) # add things, both new and duplicates

    Will not keep extending PATH with duplicates every time you source it:

    % source foo.csh % echo $PATH % /bin:/usr/bin:.:/mycode:/hercode % source foo.csh % echo $PATH % /bin:/usr/bin:.:/mycode:/hercode

    set -f there ensures that only the first occurrence of each PATH element is kept.

    0 讨论(0)
  • 2020-11-27 05:56

    I always set my path from scratch in .cshrc. That is I start off with a basic path, something like:

    set path = (. ~/bin /bin /usr/bin /usr/ucb /usr/bin/X11)
    

    (depending on the system).

    And then do:

    set path = ($otherPath $path)
    

    to add more stuff

    0 讨论(0)
提交回复
热议问题