Created
October 7, 2016 15:18
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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