top | item 43195432

(no title)

nsb1 | 1 year ago

I cribbed these from someplace - slightly different approach:

  ###################################################################
  # Add directory to path
  pathadd() {          
      newelement=${1%/}
      if [ -d "$1" ] && ! echo $PATH | grep -E -q "(^|:)$newelement($|:)" ; then
          if [ "$2" = "after" ] ; then
              PATH="$PATH:$newelement"
          else         
              PATH="$newelement:$PATH"
          fi
      fi
  }
 
  ###################################################################
  # Remove directory from path
  pathrm() {
      PATH="$(echo $PATH | sed -e "s;\(^\|:\)${1%/}\(:\|\$\);\1\2;g" -e \
      's;^:\|:$;;g' -e 's;::;:;g')"
  }

discuss

order

simonmic|1 year ago

Do any of these guard against an empty value on either side ?

"export PATH=$DIR:$PATH - That particular pattern is way too common, and is very dangerous if you consider the case when [$DIR or] $PATH (or whatever your variable is, like $LD_LIBRARY_PATH) isn’t set. Then, the value will be :/path/to/dir, which usually means both /path/to/dir and the current directory, which is usually both unexpected behaviour and a security concern."

ceph_|1 year ago

I'm surprised both the blog post and all the other comments don't mention how it should have logic to check if the item exists in the path before adding it. Otherwise you get duplicates added everytime you source your config.

Your function does that so +1. Though I'd use

    [[ $PATH =~ "(^|:)$newelement($|:)" ]] 
over grep -q but it functions the same.

rascul|1 year ago

Another option is to set the full $PATH value explicitly instead of doing an add thing for each directory. This avoids duplicates and the extra logic, but maybe isn't as convenient.