os/shell/ TidyPath


This tidies your PATH. Usage:

PATH="$(tidypath -c "$HOME/bin" "/path/to/in" -p)"

where -c means it checks for the presence of each directory, and -p inserts the current PATH. I usually use Python these days, but Perl starts more quickly, and that is important when this is called from your .bashrc.

#!/usr/bin/perl
# give PATH variable(s) on the command line
# duplicates are removed, and with the -c option, non-existing directories are removed
%a = ();
@a = ();
$check = 0;
for(@ARGV) {
  if($_ eq "-c") {
    $check = 1;
    next;
  }
  if( $_ eq "-p" ) {
    $_ = $ENV{"PATH"};
  }
  @b = split /:/;
  for $b(@b) {
    unless($a{$b}) {
      $a{$b} = $b;
      next unless(! $b eq "");
      next if( $check and ! -d $b );  # skip nonexisting paths
      push @a, $b;
    }
  }
}
$p = join ":", @a;
print $p."\n";