From Gentle Lemur, 1 Week ago, written in Plain Text.
  1. #!/bin/sh
  2. # Add to $PATH without breaking everything. Also removes duplicates, and extra :
  3. # Example: `PATH="$(fixpath)" && export PATH`
  4.  
  5. fixpath(){
  6.   local usage="usage: fixpath [[-p|--prepend] DIR | [-a|--append] DIR]"
  7.   [[ "$1" =~ -(\?|h|-help) ]] && printf "%s" "${usage}" && return
  8.  
  9.   [[ ! "${TERM##*-}" == "m" ]] && tco="\x1b[1m\x1b[31m" && sgr="\x1b[0m"
  10.  
  11.  
  12.   echo "${PATH}" | awk -v inpath="${PATH}" -v pos="${1:-NULL}" -v dir="${2}" \
  13.     -v usage="${usage}" -v tco="${tco}" -v sgr="${sgr}" '
  14.     BEGIN{FS="\n";RS=":"; ORS=""; split(inpath, path, /:+/)
  15.       {if(pos !~ /^(-a|-p|--prepend|--append|NULL)$/) bail("invalid arg", "`"pos"`")}
  16.       {if(pos != "NULL" && dir == "") bail("missing dirname", "`"dir"`")}
  17.     }
  18.     {for(d in path) {if(dir == path[d]) {pos=""; bail("duplicate entry ", "`"path[d]"`")} }}
  19.  
  20.     function bail (scream, sa, sb ,sc) {
  21.       printf(tco"bailing out!"sgr" reason: %s%s%s%s\n", scream, sa, sb, sc) >"/dev/fd/2"
  22.       printf("%s\n", usage) >"/dev/fd/2"
  23.       print "\ninput was -- " >"/dev/fd/2"; print inpath "\n"
  24.       exit 1
  25.     }
  26.  
  27.     function sanitize () {
  28.       for(i=1;i<=NR;i++) {
  29.         {if(!A[$i]++ && $i != "")
  30.           {if(length(A) !=1 )
  31.             {printf(":%s", $i)}
  32.           else
  33.             {printf("%s", $i)} }}}
  34.     }
  35.  
  36.  
  37.     {if(pos ~ /^-(p|-prepend)$/) {print dir ":"; pos=""}}
  38.     {sanitize()}
  39.  
  40.     END{{last=$FNR} {if($last ~ dir)exit}
  41.       {if(pos ~ /^-(a|-append)$/) {print ":" dir}}
  42.     }
  43.   '
  44. }
  45.  
  46. fixpath "$@"
captcha