view .shell.d/00.path_manipulation.sh @ 525:b0fa9e7cadac

shell: speed things up by golfing out grep
author Augie Fackler <raf@durin42.com>
date Mon, 14 Nov 2022 10:46:11 -0500
parents 10811c923fc0
children
line wrap: on
line source

# Functions for manipulating $PATH. Split out so I can use them in .zshenv if I want.

function insert_path_element() {
  insert_element_into_var $1 PATH
}

function remove_path_element() {
  remove_element_from_var $1 PATH
}

function insert_element_into_var () {
  eval varcontents=\$"$2"
  eval varname="$2"
  newcomp="$1"
  if [[ "$varcontents" =~ "${newcomp}:" ]] ; then
    true
  elif [[ -z "$varcontents" ]] ; then
    export $varname="$newcomp"
  else
    export $varname="$newcomp:$varcontents"
  fi
}

function remove_element_from_var() {
  eval varcontents=\$"$2"
  eval varname="$2"
  newcomp="$1"
  if echo "$varcontents" | grep "$newcomp:" >> /dev/null; then
    export $varname="`echo $varcontents | sed s%$newcomp:%%`"
  elif [[ "$varcontents" == "$newcomp" ]] ; then
    unset $varname
  fi
}

function append_path_element() {
    export PATH="${PATH}:$1"
}