Created
September 17, 2012 21:51
-
-
Save joeyates/3740014 to your computer and use it in GitHub Desktop.
Pure bash scripts for removing duplicates from PATH
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
#!/bin/bash | |
# A pure-bash (3.x+) function for removing duplicates from PATH | |
# Use: | |
# $ export PATH=`uniq-path-bash3.sh` | |
# Separate on ':' | |
OLD_IFS=$IFS | |
IFS=":" | |
# Collect unique items in NEW_PATH | |
NEW_PATH="" | |
for I in $PATH | |
do | |
REGEX="(^|:)$I(:|$)" | |
# Is the path already present? | |
if [[ ! $NEW_PATH =~ $REGEX ]]; then | |
# Is this the first item? | |
if [ -z "$NEW_PATH" ]; then | |
NEW_PATH="$I" | |
else | |
NEW_PATH="$NEW_PATH:$I" | |
fi | |
fi | |
done | |
# Re-instate old file separator | |
IFS="$OLD_IFS" | |
echo "$NEW_PATH" |
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
#!/bin/bash | |
# A pure-bash (4.x+) function for removing duplicates from PATH | |
# Use: | |
# $ export PATH=`uniq-path-bash4.sh` | |
KEEP=() | |
declare -A SEEN | |
OLD_IFS=$IFS | |
IFS=":" | |
for I in $PATH | |
do | |
if [[ ${SEEN[$I]} != 1 ]]; then | |
KEEP+=($I) | |
SEEN[$I]=1 | |
fi | |
done | |
echo "${KEEP[*]}" | |
IFS=$OLD_IFS |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment