Remove duplicate and nonexistent directories from PATH
#!/usr/bin/awk -f
#
# Remove duplicate and nonexistent directories from PATH
#
# Dir. names must not contain newlines or `:'; everything
# else should be OK.
#
# Usage: export PATH="$(repath "$PATH")" (sh) OR
# export PATH="$(repath)" OR
# setenv PATH "`repath "$PATH"`" (csh) OR
# setenv PATH "`repath`"
# Quote `arg' for shell
function q(arg, s)
{
s = arg
gsub(/'/, "'\\''", s) # first, turn every ' -> '\''
return "'"s"'" # then, single-quote the whole thing
}
BEGIN {
path = ARGC == 2 ? ARGV[1] : ENVIRON["PATH"]
sep = ":"
n = split(path, P, sep)
for (i = 1; i <= n; i++) {
dir = P[i] == "" ? "." : P[i]
if (H[dir]++ == 0 &&
system(sprintf("test -d %s", q(dir))) == 0)
printf("%s%s", c++ == 0 ? "" : sep, dir)
}
if (c) printf("\n");
}
To use this script, put something like this towards the end of your ~/.profile
or ~/.shrc
--after all PATHs have been set:
export PATH="$(repath "$PATH")"
csh
users should use this in their ~/.login
or ~/.cshrc
files:
setenv PATH "`repath "$PATH"`"