Skip to content

Instantly share code, notes, and snippets.

@dyoung522
Last active November 22, 2015 10:32
Show Gist options
  • Save dyoung522/349046b99aaf65c1c80e to your computer and use it in GitHub Desktop.
Save dyoung522/349046b99aaf65c1c80e to your computer and use it in GitHub Desktop.
pathmunge() bash function to add to PATH without duplication
pathmunge () {
if [ "$2" = "force" ] || ! echo $PATH | $(which egrep) -q "(^|:)$1($|:)"
then
if [ "$2" = "after" ]
then
PATH=$PATH:$1
else
PATH=$1:$PATH
fi
export PATH
fi
}
@dyoung522
Copy link
Author

Usage: pathmunge <new_path> [after|force]

Adds new_path to the beginning of PATH unless it already exists.

Options:
    after : Add new_path to the end of PATH
    force : Add new_path regardless of duplicates

@oxnz
Copy link

oxnz commented Nov 22, 2015

There's no quote for the PATH assignments, then if there's space or something alike in "$1" or "$PATH", then the function behaviour is undefined.

And also, why bother using which and egrep, they are external commands and just too slow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment