Skip to content

Instantly share code, notes, and snippets.

@beugley
Created October 7, 2016 15:18
Show Gist options
  • Save beugley/1f72e49a5b29adb03b486835fd1cdd86 to your computer and use it in GitHub Desktop.
Save beugley/1f72e49a5b29adb03b486835fd1cdd86 to your computer and use it in GitHub Desktop.
bash/ksh function to add an entry to the head or tail of a path. Existing duplicate entries are removed.
function add_to_path
{
# Adds an entry to the path (adds to the head by default).
# If the entry already exists, it is removed from its current location
# and added to the tail or head, as specified.
# Duplicate entries are removed.
# Examples: PATH=$(add_to_path $PATH /path/to/add head)
# LD_LIBRARY_PATH=$(add_to_path $LD_LIBRARY_PATH /path/to/add)
NEW=$(echo $1 | /bin/awk -F':' -vADD=$2 -vLOC=$3 'BEGIN {new=""}
{for (i=1;i<=NF;i++) {if ($i!=ADD)
{if (new=="") {new=$i} else {new=sprintf("%s:%s",new,$i)}}}}
END {if ($0=="") {print ADD}
else {if (LOC=="tail") {printf("%s:%s",new,ADD)}
else {printf("%s:%s",ADD,new)}}}')
echo $NEW
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment