質問

パスを設定するためにcshrcファイルに次のようなものを含めるのが一般的です:

set path = ( . $otherpath $path )

しかし、cshrcファイルを複数回ソースするとパスが重複します。重複を防ぐにはどうすればよいですか

編集:これはそれを行う1つの不潔な方法です:

set localpaths = ( . $otherpaths )
echo ${path} | egrep -i "$localpaths" >& /dev/null
if ($status != 0) then
    set path = ( . $otherpaths $path )
endif
役に立ちましたか?

解決

次のPerlスクリプトを使用して、重複のパスを削除できます。


#!/usr/bin/perl
#
# ^^ ensure this is pointing to the correct location.
#
# Title:    SLimPath
# Author:   David "Shoe Lace" Pyke <eselle@users.sourceforge.net >
#   :   Tim Nelson 
# Purpose: To create a slim version of my envirnoment path so as to eliminate
#       duplicate entries and ensure that the "." path was last.
# Date Created: April 1st 1999
# Revision History:
#   01/04/99: initial tests.. didn't wok verywell at all
#       : retreived path throught '$ENV' call
#   07/04/99: After an email from Tim Nelson <wayland@ne.com.au> got it to
#         work.
#       : used 'push' to add to array
#       : used 'join' to create a delimited string from a list/array.
#   16/02/00: fixed cmd-line options to look/work better
#   25/02/00: made verbosity level-oriented
#
#

use Getopt::Std;

sub printlevel;

$initial_str = "";
$debug_mode = "";
$delim_chr = ":";
$opt_v = 1;

getopts("v:hd:l:e:s:");

OPTS: {
    $opt_h && do {
print "\n$0 [-v level] [-d level] [-l delim] ( -e varname | -s strname | -h )";
print "\nWhere:";
print "\n   -h  This help";
print "\n   -d  Debug level";
print "\n   -l  Delimiter (between path vars)";
print "\n   -e  Specify environment variable (NB: don't include \$ sign)";
print "\n   -s  String (ie. $0 -s \$PATH:/looser/bin/)";
print "\n   -v  Verbosity (0 = quiet, 1 = normal, 2 = verbose)";
print "\n";
        exit;
    };
    $opt_d && do {
        printlevel 1, "You selected debug level $opt_d\n";
        $debug_mode = $opt_d;
    };
    $opt_l && do {
        printlevel 1, "You are going to delimit the string with \"$opt_l\"\n";
        $delim_chr = $opt_l;
    };
    $opt_e && do {
        if($opt_s) { die "Cannot specify BOTH env var and string\n"; }
        printlevel 1, "Using Environment variable \"$opt_e\"\n";
        $initial_str = $ENV{$opt_e};
    };
    $opt_s && do {
        printlevel 1, "Using String \"$opt_s\"\n";
        $initial_str = $opt_s;
    };
}

if( ($#ARGV != 1) and !$opt_e and !$opt_s){
    die "Nothing to work with -- try $0 -h\n";
}

$what = shift @ARGV;
# Split path using the delimiter
@dirs = split(/$delim_chr/, $initial_str);

$dest;
@newpath = ();
LOOP: foreach (@dirs){
    # Ensure the directory exists and is a directory
    if(! -e ) { printlevel 1, "$_ does not exist\n"; next; }
    # If the directory is ., set $dot and go around again
    if($_ eq '.') { $dot = 1; next; }

#   if ($_ ne `realpath $_`){
#           printlevel 2, "$_ becomes ".`realpath $_`."\n";
#   }
    undef $dest;
    #$_=Stdlib::realpath($_,$dest);
    # Check for duplicates and dot path
    foreach $adir (@newpath) { if($_ eq $adir) { 
        printlevel 2, "Duplicate: $_\n";
        next LOOP; 
    }}

    push @newpath, $_;
}

# Join creates a string from a list/array delimited by the first expression
print join($delim_chr, @newpath) . ($dot ? $delim_chr.".\n" : "\n");

printlevel 1, "Thank you for using $0\n";
exit;

sub printlevel {
    my($level, $string) = @_;

    if($opt_v >= $level) {
        print STDERR $string;
    }
}

私はそれが役に立つことを願っています。

他のヒント

特定のフォルダが$ PATHに既に存在する場合、誰もtr ":" "\n" | grep -xテクニックを使用して検索しなかったことに驚いています。しない理由は?

1行:

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

これは、$ PATHに複数のフォルダーを一度に追加するために自分で作成した関数です(<!> quot; aaa:bbb:ccc <!> quot;表記法を引数として使用)、追加する前にそれぞれの重複をチェックします:

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"
}

次のようなスクリプトで呼び出すことができます:

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

次の利点があります:

  • バシズムやシェル固有の構文はありません。 !#/bin/sh(ダッシュでテスト済み)
  • で完全に動作します
  • 複数のフォルダを一度に追加できます
  • ソートなし、フォルダーの順序を保持
  • フォルダ名のスペースを完全に扱う
  • 1つのテストは、$ folderが開始、終了、中間、または$ PATH内の唯一のフォルダーであるかどうかに関係なく機能します(したがって、x:*、*:x、:x:のテストを回避します) 、x、ここでのソリューションの多くが暗黙的に行うように)
  • $ PATHが<!> quot;:<!> quot;で始まるか終わる場合、または<!> quot; :: <!> quot;その中(現在のフォルダーを意味する)
  • 不要なawkまたはsedは必要ありません。
  • EPAフレンドリー;)元のIFS値は保持され、他のすべての変数は関数スコープに対してローカルです。

役立つことを願っています!

ok、cshではではありませんですが、これが$ HOME / binをbashのパスに追加する方法です...

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

季節を味わう...

10年のほとんどの間、次の(Bourne / Korn / POSIX / Bash)スクリプトを使用しています。

:   "@(#)$Id: clnpath.sh,v 1.6 1999/06/08 23:34:07 jleffler Exp $"
#
#   Print minimal version of $PATH, possibly removing some items

case $# in
0)  chop=""; path=${PATH:?};;
1)  chop=""; path=$1;;
2)  chop=$2; path=$1;;
*)  echo "Usage: `basename $0 .sh` [$PATH [remove:list]]" >&2
    exit 1;;
esac

# Beware of the quotes in the assignment to chop!
echo "$path" |
${AWK:-awk} -F: '#
BEGIN   {   # Sort out which path components to omit
            chop="'"$chop"'";
            if (chop != "") nr = split(chop, remove); else nr = 0;
            for (i = 1; i <= nr; i++)
                omit[remove[i]] = 1;
        }
{
    for (i = 1; i <= NF; i++)
    {
        x=$i;
        if (x == "") x = ".";
        if (omit[x] == 0 && path[x]++ == 0)
        {
            output = output pad x;
            pad = ":";
        }
    }
    print output;
}'

Kornシェルでは、次を使用します。

export PATH=$(clnpath /new/bin:/other/bin:$PATH /old/bin:/extra/bin)

これにより、新しいディレクトリと他のbinディレクトリを含むPATHと、メインパス値の各ディレクトリ名のコピーが残ります。ただし、古いbinディレクトリと余分なbinディレクトリはbinが削除されます。

これをCシェルに適合させる必要があります(ごめん-しかし、私は Cシェルプログラミングは有害と見なされます)。主に、コロン区切り文字をいじる必要はないので、実際には生活が楽になります。

まあ、パスの順序を気にしないのであれば、次のようなことができます:

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

これにより、パスがソートされ、同じ余分なパスが削除されます。あなたが持っている場合 。パスで、grep -vを使用して削除し、最後に追加し直したい場合があります。

これはソートなしの長いワンライナーです:
パスを設定=(echo $path | tr ' ' '\n' | perl -e 'while (<>) { print $_ unless $s{$_}++; }' | tr '\n' ' '

dr_peper、

私は通常、私が住んでいるシェルのスクリプト機能に固執することを好みます。だから、私はcshスクリプトを使用したソリューションが気に入りました。 localdirsのディレクトリごとに動作するように拡張して、自分で動作するようにしました。

foreach dir ( $localdirs )
    echo ${path} | egrep -i "$dir" >& /dev/null
    if ($status != 0) then
        set path = ( $dir $path )
    endif
end

sed(1)を使用して重複を削除します。

$ PATH=$(echo $PATH | sed -e 's/$/:/;s/^/:/;s/:/::/g;:a;s#\(:[^:]\{1,\}:\)\(.*\)\1#\1\2#g;ta;s/::*/:/g;s/^://;s/:$//;')

これにより、最初のインスタンスの後の重複が削除されます。これは、必要な場合とそうでない場合があります。例:

$ NEWPATH=/bin:/usr/bin:/bin:/usr/local/bin:/usr/local/bin:/bin
$ echo $NEWPATH | sed -e 's/$/:/; s/^/:/; s/:/::/g; :a; s#\(:[^:]\{1,\}:\)\(.*\)\1#\1\2#g; t a; s/::*/:/g; s/^://; s/:$//;'
/bin:/usr/bin:/usr/local/bin
$

お楽しみください

ここに私が使用しているものがあります-おそらく他の誰かが役に立つでしょう:

#!/bin/csh
#  ABSTRACT
#    /bin/csh function-like aliases for manipulating environment
#    variables containing paths.
#
#  BUGS
#    - These *MUST* be single line aliases to avoid parsing problems apparently related
#      to if-then-else
#    - Aliases currently perform tests in inefficient in order to avoid parsing problems
#    - Extremely fragile - use bash instead!!
#
#  AUTHOR
#    J. P. Abelanet - 11/11/10

#  Function-like alias to add a path to the front of an environment variable
#    containing colon (':') delimited paths, without path duplication
#
#  Usage: prepend_path ENVVARIABLE /path/to/prepend
alias prepend_path \
  'set arg2="\!:2";  if ($?\!:1 == 0) setenv \!:1 "$arg2";  if ($?\!:1 && $\!:1 !~ {,*:}"$arg2"{:*,}) setenv \!:1 "$arg2":"$\!:1";'

#  Function-like alias to add a path to the back of any environment variable 
#    containing colon (':') delimited paths, without path duplication
#
#  Usage: append_path ENVVARIABLE /path/to/append
alias append_path \
  'set arg2="\!:2";  if ($?\!:1 == 0) setenv \!:1 "$arg2";  if ($?\!:1 && $\!:1 !~ {,*:}"$arg2"{:*,}) setenv \!:1 "$\!:1":"$arg2";'

.cshrcで常に最初からパスを設定します。 つまり、次のような基本的なパスから始めます。

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

(システムに依存)。

そして次に:

set path = ($otherPath $path)

より多くのものを追加する

元の質問と同じニーズがあります。 以前の回答に基づいて、Korn / POSIX / Bashで使用しました:

export PATH=$(perl -e 'print join ":", grep {!$h{$_}++} split ":", "'$otherpath:$PATH\")

cshで直接翻訳するのが困難でした(cshのエスケープルールは非常識です)。私は使用しました(dr_pepperが示唆するように):

set path = ( `echo $otherpath $path | tr ' ' '\n' | perl -ne 'print $_ unless $h{$_}++' | tr '\n' ' '`)

さらに単純化する(パイプの数を減らす)アイデアはありますか?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top