Skip to content

Instantly share code, notes, and snippets.

@firstval
Created September 17, 2015 10:30
Show Gist options
  • Save firstval/faa4bb1dd95bd3d93878 to your computer and use it in GitHub Desktop.
Save firstval/faa4bb1dd95bd3d93878 to your computer and use it in GitHub Desktop.
Removing PATH on LINUX
So, combining the answers from @gilles and @bruno-a (and a couple of other sed tricks) I came up with this one-liner, which will remove (every) REMOVE_PART from PATH, regardless of whether it occurs at the beginning, middle or end of PATH
PATH=$(REMOVE_PART="/d/Programme/cygwin/bin" sh -c 'echo ":$PATH:" | sed "s@:$REMOVE_PART:@:@g;s@^:\(.*\):\$@\1@"')
It's a bit unwieldy, but it's nice to be able to do it in one hit. The ; is used to join together the two separate sed commands:
s@:$REMOVE_PART:@:@g (which replaces :$REMOVE_PART: with a single :)
s@^:\(.*\):\$@\1@ (which strips off the leading and trailing colons we added with the echo command)
And along similar lines, I've just managed to come up with this one-liner for adding a ADD_PART to the PATH, only if the PATH doesn't already contain it
PATH=$(ADD_PART="/d/Programme/cygwin/bin" sh -c 'if echo ":$PATH:" | grep -q ":$ADD_PART:"; then echo "$PATH"; else echo "$ADD_PART:$PATH"; fi')
Change the last part to echo "$PATH:$ADD_PART" if you want to add ADD_PART to the end of PATH instead of to the start.
...
...or to make this even easier, create a script called remove_path_part with the contents
echo ":$PATH:" | sed "s@:$1:@:@g;s@^:\(.*\):\$@\1@"
and a script called prepend_path_part with the contents
if echo ":$PATH:" | grep -q ":$1:"; then echo "$PATH"; else echo "$1:$PATH"; fi
and a script called append_path_part with the contents
if echo ":$PATH:" | grep -q ":$1:"; then echo "$PATH"; else echo "$PATH:$1"; fi
make them all executable, and then call them like:
PATH=$(remove_path_part /d/Programme/cygwin/bin)
PATH=$(prepend_path_part /d/Programme/cygwin/bin)
PATH=$(append_path_part /d/Programme/cygwin/bin)
Neat, even if I say so myself :-)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment