[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Bash: testing a variable



On Fri, Jul 09, 2021 at 01:54:19PM -0600, Charles Curley wrote:
> I'd like to check two things:
> 
> * Whether a given path is not already in the $PATH variable
> 
> * Whether the given path already exists
> 
> If both are true, I'd like to add the given path to the $PATH variable.

add_path_maybe() {
  local p i

  if [[ $1 != /* ]]; then
    echo "refusing to consider a directory that doesn't begin with /" >&2
    return 1
  fi

  if [[ ! -d $1 ]]; then
    echo "directory '$1' does not exist" >&2
    return 1
  fi

  IFS=: read -ra p <<< "$PATH"
  for i in "${p[@]}"; do
    if [[ $i = "$1" ]]; then
      return 0
    fi
  done

  PATH=$PATH:$1
}


Reply to: