Removing a directory from PATHHow can I find the program I'm hiding in bashBash: why isn't “set”...

LINQ Extension methods MinBy and MaxBy

Quick Tilepaint Puzzles: Corridors and Corners

What kind of electrical outlet is this? Red, winking-face shape

Break down the phrase "shitsurei shinakereba naranaindesu"

Sum and average calculator

Received email from ISP saying one of my devices has malware

A word for the urge to do the opposite

apt-file regex: find multiple packages at once using or

Create a list of snaking numbers under 50,000

How to investigate an unknown 1.5GB file named "sudo" in my Linux home directory?

How can I improve my formal definitions?

What caused the end of cybernetic implants?

Did NASA/JPL get "waning" and "waxing" backwards in this video?

Turn off Google Chrome's Notification for "Flash Player will no longer be supported after December 2020."

Heuristic argument for the Riemann Hypothesis

How to run a command 1 out of N times in Bash

Why do presidential pardons exist in a country having a clear separation of powers?

What is the practical impact of using System.Random which is not cryptographically random?

Fishing from underwater domes

Why haven't the British protested Brexit as ardently as the Hong Kong protesters?

When you have to wait for a short time

Unreadable lines of Milnor's book

Ideas behind the 8.Bd3 line in the 4.Ng5 Two Knights Defense

How to Calculate this definite integral or how to solve this series?



Removing a directory from PATH


How can I find the program I'm hiding in bashBash: why isn't “set” behaving like I expect it to?how to get a variable's definition fileDoes a duplicate entries in a PATH variable revoke the precedence given by the first entry?Change my profile's PATH environment variable on CygwinChange Environment Path Variable OrderPATH not getting exported from ~/.profile until manually sourcedWhy do some processes set $PATH manually?How To Find All Locations Where $PATH is SetGet the normal $PATH when calling it in a subshellPortable way to run command without PATH from bash script






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







28















I'm trying to compile wxWidgets using MingW, and I have cygwin in my path, which seems to conflict. So I would like to remove /d/Programme/cygwin/bin from the PATH variable and I wonder if there is some elegant way to do this.



The naive approach would be to echo it to a file, remove it manually and source it, but I bet there is better approach to this.










share|improve this question






















  • 2





    Many techniques are listed here: stackoverflow.com/questions/370047/…

    – slm
    Jan 11 '14 at 14:41


















28















I'm trying to compile wxWidgets using MingW, and I have cygwin in my path, which seems to conflict. So I would like to remove /d/Programme/cygwin/bin from the PATH variable and I wonder if there is some elegant way to do this.



The naive approach would be to echo it to a file, remove it manually and source it, but I bet there is better approach to this.










share|improve this question






















  • 2





    Many techniques are listed here: stackoverflow.com/questions/370047/…

    – slm
    Jan 11 '14 at 14:41














28












28








28


12






I'm trying to compile wxWidgets using MingW, and I have cygwin in my path, which seems to conflict. So I would like to remove /d/Programme/cygwin/bin from the PATH variable and I wonder if there is some elegant way to do this.



The naive approach would be to echo it to a file, remove it manually and source it, but I bet there is better approach to this.










share|improve this question
















I'm trying to compile wxWidgets using MingW, and I have cygwin in my path, which seems to conflict. So I would like to remove /d/Programme/cygwin/bin from the PATH variable and I wonder if there is some elegant way to do this.



The naive approach would be to echo it to a file, remove it manually and source it, but I bet there is better approach to this.







bash shell environment-variables path






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 11 '14 at 21:41









Gilles

572k139 gold badges1182 silver badges1693 bronze badges




572k139 gold badges1182 silver badges1693 bronze badges










asked Jan 11 '14 at 13:44









DevolusDevolus

2461 gold badge3 silver badges6 bronze badges




2461 gold badge3 silver badges6 bronze badges











  • 2





    Many techniques are listed here: stackoverflow.com/questions/370047/…

    – slm
    Jan 11 '14 at 14:41














  • 2





    Many techniques are listed here: stackoverflow.com/questions/370047/…

    – slm
    Jan 11 '14 at 14:41








2




2





Many techniques are listed here: stackoverflow.com/questions/370047/…

– slm
Jan 11 '14 at 14:41





Many techniques are listed here: stackoverflow.com/questions/370047/…

– slm
Jan 11 '14 at 14:41










9 Answers
9






active

oldest

votes


















22















There are no standard tools to "edit" the value of $PATH (i.e. "add folder only when it doesn't already exists" or "remove this folder").
You just execute:



export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games


that would be for the current session, if you want to change permanently add it to any .bashrc, bash.bashrc, /etc/profile - whatever fits your system and user needs.
However if you're using BASH, you can also do the following if, let's say, you want to remove the directory /home/wrong/dir/ from your PATH variable, assuming it's at the end:



PATH=$(echo "$PATH" | sed -e 's/:/home/wrong/dir$//')


So in your case you may use



PATH=$(echo "$PATH" | sed -e 's/:/d/Programme/cygwin/bin$//')





share|improve this answer























  • 1





    If the path in question is at the beginning of the PATH variable, you need to match the colon at the end. This is an annoying caveat which complicates easy generic manipulations of PATH variables.

    – Graeme
    Jan 11 '14 at 13:58








  • 4





    When dealing with so many slashes I prefer to change the regex delimiter / with something like |: PATH=$(echo "$PATH" | sed -e 's|:/d/Programme/cygwin/bin$||') to prevent all the escaping.

    – Matthias Kuhn
    Mar 17 '16 at 12:06



















16















In bash:



directory_to_remove=/d/Programme/cygwin/bin
PATH=:$PATH:
PATH=${PATH//:$directory_to_remove:/:}
PATH=${PATH#:}; PATH=${PATH%:}


If you don't use an intermediate variable, you need to protect the / characters in the directory to remove so that they aren't treated as the end of the search text.



PATH=:$PATH:
PATH=${PATH//:/d/Programme/cygwin/bin:/:}
PATH=${PATH#:}; PATH=${PATH%:}


The first and third line are there to arrange for every component of the search path to be surrounded by :, to avoid special-casing the first and last component. The second line removes the specified component.






share|improve this answer




























  • Thanks @Gilles, your answer prompted me to come up with my own solution, which only requires three manipulations of PATH rather then four. *8')

    – Mark Booth
    Jun 23 '16 at 11:36



















8















After considering other options presented here, and not fully understanding how some of them worked I developed my own path_remove function, which I added to my .bashrc:



function path_remove {
# Delete path by parts so we can never accidentally remove sub paths
PATH=${PATH//":$1:"/":"} # delete any instances in the middle
PATH=${PATH/#"$1:"/} # delete any instance at the beginning
PATH=${PATH/%":$1"/} # delete any instance in the at the end
}


This ended up pretty close to Gilles' solution but wrapped up as a bash function which could be easily used on the command line.



It has the advantages that as a bash function it works like a program without needing to be a program on the path, and it doesn't require any external programs to run, just bash string manipulation.



It appears pretty robust, in particular it doesn't turn somepath:mypath/mysubpath into somepath/mysubpath:if you run path_remove mypath, which was a problem I had with my previous path_remove function.



An excellent explanation of how bash string manipulation works can be found at the Advanced Bash-Scripting Guide.






share|improve this answer



































    3















    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 :-)






    share|improve this answer




























    • I like the suggestion, especially the idea with the scripts.

      – Devolus
      Jan 13 '15 at 9:06



















    2















    It is an interesting exercise to write a bash function to remove a directory from a path variable.



    Here are some functions I use in my .bash* files to append/prepend directories to paths. They have the virtue of removing duplicate entries, if any, and work with any kind of colon separated path variable (PATH, MANPATH, INFOPATH, ...). the remove_from function removes the directory.



    # {app,pre}pend_to path-var-name dirpath
    # remove_from path-var-name dirpath
    #
    # Functions to manipulate a path-style variable. {app,pre}pend_to
    # both remove any other instances of dirname before adding it to
    # the start or end of the path-var-name variable.
    #
    # Calling example:
    # append_to PATH "/usr/local/bin"
    #
    # Uses eval to allow target path varname to be passed in.
    function remove_from() {
    # add surrounging colons
    eval tmp_path=":$${1}:"
    # if dir is already there, remove it
    (echo "${tmp_path}" | grep --silent ":${2}:") &&
    tmp_path=`echo "$tmp_path" | sed "s=:${2}:=:=g"`
    # remove surrounding colons
    tmp_path=`echo "$tmp_path" | sed 's=^:==; s=:$=='`
    eval export $1="$tmp_path"
    }
    function append_to() {
    remove_from "$1" "$2" # clean the path contents
    eval export $1="$${1}:$2"
    }
    function prepend_to() {
    remove_from "$1" "$2" # clean the path contents
    eval export $1="${2}:$$1"
    }





    share|improve this answer

































      2















      Below are revised code from Greg Tarsa's solution. Only bash build-in commands are used here. Thus, it will save a lots of fork() system calls.



      # Calling example:
      # append_to PATH "/usr/local/bin"

      function remove_from()
      {
      local path="${1}"
      local dir="${2}"
      local -a dirs=()
      local old_ifs="${IFS}"
      IFS=":"
      set -- ${!path}
      while [ "$#" -gt "0" ]
      do
      [ "${1}" != "${dir}" ] && dirs+=("${1}")
      shift
      done
      eval "export ${path}="${dirs[*]}""
      IFS="${old_ifs}"
      }

      function append_to()
      {
      remove_from "${1}" "${2}"
      [ -d "${2}" ] || return
      if [ -n "${!1}" ]
      then
      eval "export ${1}="${!1}:${2}""
      else
      eval "export ${1}="${2}""
      fi
      }

      function prepend_to()
      {
      remove_from "${1}" "${2}"
      [ -d "${2}" ] || return
      if [ -n "${!1}" ]
      then
      eval "export ${1}="${2}:${!1}""
      else
      eval "export ${1}="${2}""
      fi
      }





      share|improve this answer



































        1















        To complete/improve the accepted answer from Tushar, you can:




        • avoid having to escape the slashes in the PATH by using non-slash delimiters

        • omit the -e option, as per the sed man page: "If no -e, --expression, -f, or --file option is given, then the first non-option argument is taken as the sed script to interpret."

        • use the g (global) flag to remove all occurrences


        In the end, it gives something like this:



        PATH=$(echo "$PATH" | sed 's@:/home/wrong/dir$@@g')





        share|improve this answer

































          1















          Much simpler one liner.




          export PATH=`echo $PATH | tr ":" "n" | grep -v "anaconda" | tr "n" ":"`







          share|improve this answer

































            0















            The current answers don't solve my similar problem in that I need to remove multiple paths. All these paths are sub-directories of a single directory. In that case, this one-liner works for me: (suppose the pattern is cygwin, i.e., removing all paths that contains cygwin)



            pattern=cygwin; export PATH=$(echo $PATH|tr ':' 'n'|sed "#${pattern}#d" |tr 'n' ':')





            share|improve this answer




























              Your Answer








              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "106"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f108873%2fremoving-a-directory-from-path%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              9 Answers
              9






              active

              oldest

              votes








              9 Answers
              9






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              22















              There are no standard tools to "edit" the value of $PATH (i.e. "add folder only when it doesn't already exists" or "remove this folder").
              You just execute:



              export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games


              that would be for the current session, if you want to change permanently add it to any .bashrc, bash.bashrc, /etc/profile - whatever fits your system and user needs.
              However if you're using BASH, you can also do the following if, let's say, you want to remove the directory /home/wrong/dir/ from your PATH variable, assuming it's at the end:



              PATH=$(echo "$PATH" | sed -e 's/:/home/wrong/dir$//')


              So in your case you may use



              PATH=$(echo "$PATH" | sed -e 's/:/d/Programme/cygwin/bin$//')





              share|improve this answer























              • 1





                If the path in question is at the beginning of the PATH variable, you need to match the colon at the end. This is an annoying caveat which complicates easy generic manipulations of PATH variables.

                – Graeme
                Jan 11 '14 at 13:58








              • 4





                When dealing with so many slashes I prefer to change the regex delimiter / with something like |: PATH=$(echo "$PATH" | sed -e 's|:/d/Programme/cygwin/bin$||') to prevent all the escaping.

                – Matthias Kuhn
                Mar 17 '16 at 12:06
















              22















              There are no standard tools to "edit" the value of $PATH (i.e. "add folder only when it doesn't already exists" or "remove this folder").
              You just execute:



              export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games


              that would be for the current session, if you want to change permanently add it to any .bashrc, bash.bashrc, /etc/profile - whatever fits your system and user needs.
              However if you're using BASH, you can also do the following if, let's say, you want to remove the directory /home/wrong/dir/ from your PATH variable, assuming it's at the end:



              PATH=$(echo "$PATH" | sed -e 's/:/home/wrong/dir$//')


              So in your case you may use



              PATH=$(echo "$PATH" | sed -e 's/:/d/Programme/cygwin/bin$//')





              share|improve this answer























              • 1





                If the path in question is at the beginning of the PATH variable, you need to match the colon at the end. This is an annoying caveat which complicates easy generic manipulations of PATH variables.

                – Graeme
                Jan 11 '14 at 13:58








              • 4





                When dealing with so many slashes I prefer to change the regex delimiter / with something like |: PATH=$(echo "$PATH" | sed -e 's|:/d/Programme/cygwin/bin$||') to prevent all the escaping.

                – Matthias Kuhn
                Mar 17 '16 at 12:06














              22














              22










              22









              There are no standard tools to "edit" the value of $PATH (i.e. "add folder only when it doesn't already exists" or "remove this folder").
              You just execute:



              export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games


              that would be for the current session, if you want to change permanently add it to any .bashrc, bash.bashrc, /etc/profile - whatever fits your system and user needs.
              However if you're using BASH, you can also do the following if, let's say, you want to remove the directory /home/wrong/dir/ from your PATH variable, assuming it's at the end:



              PATH=$(echo "$PATH" | sed -e 's/:/home/wrong/dir$//')


              So in your case you may use



              PATH=$(echo "$PATH" | sed -e 's/:/d/Programme/cygwin/bin$//')





              share|improve this answer















              There are no standard tools to "edit" the value of $PATH (i.e. "add folder only when it doesn't already exists" or "remove this folder").
              You just execute:



              export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games


              that would be for the current session, if you want to change permanently add it to any .bashrc, bash.bashrc, /etc/profile - whatever fits your system and user needs.
              However if you're using BASH, you can also do the following if, let's say, you want to remove the directory /home/wrong/dir/ from your PATH variable, assuming it's at the end:



              PATH=$(echo "$PATH" | sed -e 's/:/home/wrong/dir$//')


              So in your case you may use



              PATH=$(echo "$PATH" | sed -e 's/:/d/Programme/cygwin/bin$//')






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jan 11 '14 at 23:44









              Gilles

              572k139 gold badges1182 silver badges1693 bronze badges




              572k139 gold badges1182 silver badges1693 bronze badges










              answered Jan 11 '14 at 13:53









              tusharmakkar08tusharmakkar08

              9671 gold badge13 silver badges21 bronze badges




              9671 gold badge13 silver badges21 bronze badges











              • 1





                If the path in question is at the beginning of the PATH variable, you need to match the colon at the end. This is an annoying caveat which complicates easy generic manipulations of PATH variables.

                – Graeme
                Jan 11 '14 at 13:58








              • 4





                When dealing with so many slashes I prefer to change the regex delimiter / with something like |: PATH=$(echo "$PATH" | sed -e 's|:/d/Programme/cygwin/bin$||') to prevent all the escaping.

                – Matthias Kuhn
                Mar 17 '16 at 12:06














              • 1





                If the path in question is at the beginning of the PATH variable, you need to match the colon at the end. This is an annoying caveat which complicates easy generic manipulations of PATH variables.

                – Graeme
                Jan 11 '14 at 13:58








              • 4





                When dealing with so many slashes I prefer to change the regex delimiter / with something like |: PATH=$(echo "$PATH" | sed -e 's|:/d/Programme/cygwin/bin$||') to prevent all the escaping.

                – Matthias Kuhn
                Mar 17 '16 at 12:06








              1




              1





              If the path in question is at the beginning of the PATH variable, you need to match the colon at the end. This is an annoying caveat which complicates easy generic manipulations of PATH variables.

              – Graeme
              Jan 11 '14 at 13:58







              If the path in question is at the beginning of the PATH variable, you need to match the colon at the end. This is an annoying caveat which complicates easy generic manipulations of PATH variables.

              – Graeme
              Jan 11 '14 at 13:58






              4




              4





              When dealing with so many slashes I prefer to change the regex delimiter / with something like |: PATH=$(echo "$PATH" | sed -e 's|:/d/Programme/cygwin/bin$||') to prevent all the escaping.

              – Matthias Kuhn
              Mar 17 '16 at 12:06





              When dealing with so many slashes I prefer to change the regex delimiter / with something like |: PATH=$(echo "$PATH" | sed -e 's|:/d/Programme/cygwin/bin$||') to prevent all the escaping.

              – Matthias Kuhn
              Mar 17 '16 at 12:06













              16















              In bash:



              directory_to_remove=/d/Programme/cygwin/bin
              PATH=:$PATH:
              PATH=${PATH//:$directory_to_remove:/:}
              PATH=${PATH#:}; PATH=${PATH%:}


              If you don't use an intermediate variable, you need to protect the / characters in the directory to remove so that they aren't treated as the end of the search text.



              PATH=:$PATH:
              PATH=${PATH//:/d/Programme/cygwin/bin:/:}
              PATH=${PATH#:}; PATH=${PATH%:}


              The first and third line are there to arrange for every component of the search path to be surrounded by :, to avoid special-casing the first and last component. The second line removes the specified component.






              share|improve this answer




























              • Thanks @Gilles, your answer prompted me to come up with my own solution, which only requires three manipulations of PATH rather then four. *8')

                – Mark Booth
                Jun 23 '16 at 11:36
















              16















              In bash:



              directory_to_remove=/d/Programme/cygwin/bin
              PATH=:$PATH:
              PATH=${PATH//:$directory_to_remove:/:}
              PATH=${PATH#:}; PATH=${PATH%:}


              If you don't use an intermediate variable, you need to protect the / characters in the directory to remove so that they aren't treated as the end of the search text.



              PATH=:$PATH:
              PATH=${PATH//:/d/Programme/cygwin/bin:/:}
              PATH=${PATH#:}; PATH=${PATH%:}


              The first and third line are there to arrange for every component of the search path to be surrounded by :, to avoid special-casing the first and last component. The second line removes the specified component.






              share|improve this answer




























              • Thanks @Gilles, your answer prompted me to come up with my own solution, which only requires three manipulations of PATH rather then four. *8')

                – Mark Booth
                Jun 23 '16 at 11:36














              16














              16










              16









              In bash:



              directory_to_remove=/d/Programme/cygwin/bin
              PATH=:$PATH:
              PATH=${PATH//:$directory_to_remove:/:}
              PATH=${PATH#:}; PATH=${PATH%:}


              If you don't use an intermediate variable, you need to protect the / characters in the directory to remove so that they aren't treated as the end of the search text.



              PATH=:$PATH:
              PATH=${PATH//:/d/Programme/cygwin/bin:/:}
              PATH=${PATH#:}; PATH=${PATH%:}


              The first and third line are there to arrange for every component of the search path to be surrounded by :, to avoid special-casing the first and last component. The second line removes the specified component.






              share|improve this answer















              In bash:



              directory_to_remove=/d/Programme/cygwin/bin
              PATH=:$PATH:
              PATH=${PATH//:$directory_to_remove:/:}
              PATH=${PATH#:}; PATH=${PATH%:}


              If you don't use an intermediate variable, you need to protect the / characters in the directory to remove so that they aren't treated as the end of the search text.



              PATH=:$PATH:
              PATH=${PATH//:/d/Programme/cygwin/bin:/:}
              PATH=${PATH#:}; PATH=${PATH%:}


              The first and third line are there to arrange for every component of the search path to be surrounded by :, to avoid special-casing the first and last component. The second line removes the specified component.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 2 hours ago

























              answered Jan 11 '14 at 23:42









              GillesGilles

              572k139 gold badges1182 silver badges1693 bronze badges




              572k139 gold badges1182 silver badges1693 bronze badges
















              • Thanks @Gilles, your answer prompted me to come up with my own solution, which only requires three manipulations of PATH rather then four. *8')

                – Mark Booth
                Jun 23 '16 at 11:36



















              • Thanks @Gilles, your answer prompted me to come up with my own solution, which only requires three manipulations of PATH rather then four. *8')

                – Mark Booth
                Jun 23 '16 at 11:36

















              Thanks @Gilles, your answer prompted me to come up with my own solution, which only requires three manipulations of PATH rather then four. *8')

              – Mark Booth
              Jun 23 '16 at 11:36





              Thanks @Gilles, your answer prompted me to come up with my own solution, which only requires three manipulations of PATH rather then four. *8')

              – Mark Booth
              Jun 23 '16 at 11:36











              8















              After considering other options presented here, and not fully understanding how some of them worked I developed my own path_remove function, which I added to my .bashrc:



              function path_remove {
              # Delete path by parts so we can never accidentally remove sub paths
              PATH=${PATH//":$1:"/":"} # delete any instances in the middle
              PATH=${PATH/#"$1:"/} # delete any instance at the beginning
              PATH=${PATH/%":$1"/} # delete any instance in the at the end
              }


              This ended up pretty close to Gilles' solution but wrapped up as a bash function which could be easily used on the command line.



              It has the advantages that as a bash function it works like a program without needing to be a program on the path, and it doesn't require any external programs to run, just bash string manipulation.



              It appears pretty robust, in particular it doesn't turn somepath:mypath/mysubpath into somepath/mysubpath:if you run path_remove mypath, which was a problem I had with my previous path_remove function.



              An excellent explanation of how bash string manipulation works can be found at the Advanced Bash-Scripting Guide.






              share|improve this answer
































                8















                After considering other options presented here, and not fully understanding how some of them worked I developed my own path_remove function, which I added to my .bashrc:



                function path_remove {
                # Delete path by parts so we can never accidentally remove sub paths
                PATH=${PATH//":$1:"/":"} # delete any instances in the middle
                PATH=${PATH/#"$1:"/} # delete any instance at the beginning
                PATH=${PATH/%":$1"/} # delete any instance in the at the end
                }


                This ended up pretty close to Gilles' solution but wrapped up as a bash function which could be easily used on the command line.



                It has the advantages that as a bash function it works like a program without needing to be a program on the path, and it doesn't require any external programs to run, just bash string manipulation.



                It appears pretty robust, in particular it doesn't turn somepath:mypath/mysubpath into somepath/mysubpath:if you run path_remove mypath, which was a problem I had with my previous path_remove function.



                An excellent explanation of how bash string manipulation works can be found at the Advanced Bash-Scripting Guide.






                share|improve this answer






























                  8














                  8










                  8









                  After considering other options presented here, and not fully understanding how some of them worked I developed my own path_remove function, which I added to my .bashrc:



                  function path_remove {
                  # Delete path by parts so we can never accidentally remove sub paths
                  PATH=${PATH//":$1:"/":"} # delete any instances in the middle
                  PATH=${PATH/#"$1:"/} # delete any instance at the beginning
                  PATH=${PATH/%":$1"/} # delete any instance in the at the end
                  }


                  This ended up pretty close to Gilles' solution but wrapped up as a bash function which could be easily used on the command line.



                  It has the advantages that as a bash function it works like a program without needing to be a program on the path, and it doesn't require any external programs to run, just bash string manipulation.



                  It appears pretty robust, in particular it doesn't turn somepath:mypath/mysubpath into somepath/mysubpath:if you run path_remove mypath, which was a problem I had with my previous path_remove function.



                  An excellent explanation of how bash string manipulation works can be found at the Advanced Bash-Scripting Guide.






                  share|improve this answer















                  After considering other options presented here, and not fully understanding how some of them worked I developed my own path_remove function, which I added to my .bashrc:



                  function path_remove {
                  # Delete path by parts so we can never accidentally remove sub paths
                  PATH=${PATH//":$1:"/":"} # delete any instances in the middle
                  PATH=${PATH/#"$1:"/} # delete any instance at the beginning
                  PATH=${PATH/%":$1"/} # delete any instance in the at the end
                  }


                  This ended up pretty close to Gilles' solution but wrapped up as a bash function which could be easily used on the command line.



                  It has the advantages that as a bash function it works like a program without needing to be a program on the path, and it doesn't require any external programs to run, just bash string manipulation.



                  It appears pretty robust, in particular it doesn't turn somepath:mypath/mysubpath into somepath/mysubpath:if you run path_remove mypath, which was a problem I had with my previous path_remove function.



                  An excellent explanation of how bash string manipulation works can be found at the Advanced Bash-Scripting Guide.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Apr 13 '17 at 12:37









                  Community

                  1




                  1










                  answered Jun 23 '16 at 11:34









                  Mark BoothMark Booth

                  6821 gold badge9 silver badges22 bronze badges




                  6821 gold badge9 silver badges22 bronze badges


























                      3















                      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 :-)






                      share|improve this answer




























                      • I like the suggestion, especially the idea with the scripts.

                        – Devolus
                        Jan 13 '15 at 9:06
















                      3















                      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 :-)






                      share|improve this answer




























                      • I like the suggestion, especially the idea with the scripts.

                        – Devolus
                        Jan 13 '15 at 9:06














                      3














                      3










                      3









                      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 :-)






                      share|improve this answer















                      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 :-)







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Jan 14 '15 at 10:32

























                      answered Jan 13 '15 at 3:56









                      LurchmanLurchman

                      413 bronze badges




                      413 bronze badges
















                      • I like the suggestion, especially the idea with the scripts.

                        – Devolus
                        Jan 13 '15 at 9:06



















                      • I like the suggestion, especially the idea with the scripts.

                        – Devolus
                        Jan 13 '15 at 9:06

















                      I like the suggestion, especially the idea with the scripts.

                      – Devolus
                      Jan 13 '15 at 9:06





                      I like the suggestion, especially the idea with the scripts.

                      – Devolus
                      Jan 13 '15 at 9:06











                      2















                      It is an interesting exercise to write a bash function to remove a directory from a path variable.



                      Here are some functions I use in my .bash* files to append/prepend directories to paths. They have the virtue of removing duplicate entries, if any, and work with any kind of colon separated path variable (PATH, MANPATH, INFOPATH, ...). the remove_from function removes the directory.



                      # {app,pre}pend_to path-var-name dirpath
                      # remove_from path-var-name dirpath
                      #
                      # Functions to manipulate a path-style variable. {app,pre}pend_to
                      # both remove any other instances of dirname before adding it to
                      # the start or end of the path-var-name variable.
                      #
                      # Calling example:
                      # append_to PATH "/usr/local/bin"
                      #
                      # Uses eval to allow target path varname to be passed in.
                      function remove_from() {
                      # add surrounging colons
                      eval tmp_path=":$${1}:"
                      # if dir is already there, remove it
                      (echo "${tmp_path}" | grep --silent ":${2}:") &&
                      tmp_path=`echo "$tmp_path" | sed "s=:${2}:=:=g"`
                      # remove surrounding colons
                      tmp_path=`echo "$tmp_path" | sed 's=^:==; s=:$=='`
                      eval export $1="$tmp_path"
                      }
                      function append_to() {
                      remove_from "$1" "$2" # clean the path contents
                      eval export $1="$${1}:$2"
                      }
                      function prepend_to() {
                      remove_from "$1" "$2" # clean the path contents
                      eval export $1="${2}:$$1"
                      }





                      share|improve this answer






























                        2















                        It is an interesting exercise to write a bash function to remove a directory from a path variable.



                        Here are some functions I use in my .bash* files to append/prepend directories to paths. They have the virtue of removing duplicate entries, if any, and work with any kind of colon separated path variable (PATH, MANPATH, INFOPATH, ...). the remove_from function removes the directory.



                        # {app,pre}pend_to path-var-name dirpath
                        # remove_from path-var-name dirpath
                        #
                        # Functions to manipulate a path-style variable. {app,pre}pend_to
                        # both remove any other instances of dirname before adding it to
                        # the start or end of the path-var-name variable.
                        #
                        # Calling example:
                        # append_to PATH "/usr/local/bin"
                        #
                        # Uses eval to allow target path varname to be passed in.
                        function remove_from() {
                        # add surrounging colons
                        eval tmp_path=":$${1}:"
                        # if dir is already there, remove it
                        (echo "${tmp_path}" | grep --silent ":${2}:") &&
                        tmp_path=`echo "$tmp_path" | sed "s=:${2}:=:=g"`
                        # remove surrounding colons
                        tmp_path=`echo "$tmp_path" | sed 's=^:==; s=:$=='`
                        eval export $1="$tmp_path"
                        }
                        function append_to() {
                        remove_from "$1" "$2" # clean the path contents
                        eval export $1="$${1}:$2"
                        }
                        function prepend_to() {
                        remove_from "$1" "$2" # clean the path contents
                        eval export $1="${2}:$$1"
                        }





                        share|improve this answer




























                          2














                          2










                          2









                          It is an interesting exercise to write a bash function to remove a directory from a path variable.



                          Here are some functions I use in my .bash* files to append/prepend directories to paths. They have the virtue of removing duplicate entries, if any, and work with any kind of colon separated path variable (PATH, MANPATH, INFOPATH, ...). the remove_from function removes the directory.



                          # {app,pre}pend_to path-var-name dirpath
                          # remove_from path-var-name dirpath
                          #
                          # Functions to manipulate a path-style variable. {app,pre}pend_to
                          # both remove any other instances of dirname before adding it to
                          # the start or end of the path-var-name variable.
                          #
                          # Calling example:
                          # append_to PATH "/usr/local/bin"
                          #
                          # Uses eval to allow target path varname to be passed in.
                          function remove_from() {
                          # add surrounging colons
                          eval tmp_path=":$${1}:"
                          # if dir is already there, remove it
                          (echo "${tmp_path}" | grep --silent ":${2}:") &&
                          tmp_path=`echo "$tmp_path" | sed "s=:${2}:=:=g"`
                          # remove surrounding colons
                          tmp_path=`echo "$tmp_path" | sed 's=^:==; s=:$=='`
                          eval export $1="$tmp_path"
                          }
                          function append_to() {
                          remove_from "$1" "$2" # clean the path contents
                          eval export $1="$${1}:$2"
                          }
                          function prepend_to() {
                          remove_from "$1" "$2" # clean the path contents
                          eval export $1="${2}:$$1"
                          }





                          share|improve this answer













                          It is an interesting exercise to write a bash function to remove a directory from a path variable.



                          Here are some functions I use in my .bash* files to append/prepend directories to paths. They have the virtue of removing duplicate entries, if any, and work with any kind of colon separated path variable (PATH, MANPATH, INFOPATH, ...). the remove_from function removes the directory.



                          # {app,pre}pend_to path-var-name dirpath
                          # remove_from path-var-name dirpath
                          #
                          # Functions to manipulate a path-style variable. {app,pre}pend_to
                          # both remove any other instances of dirname before adding it to
                          # the start or end of the path-var-name variable.
                          #
                          # Calling example:
                          # append_to PATH "/usr/local/bin"
                          #
                          # Uses eval to allow target path varname to be passed in.
                          function remove_from() {
                          # add surrounging colons
                          eval tmp_path=":$${1}:"
                          # if dir is already there, remove it
                          (echo "${tmp_path}" | grep --silent ":${2}:") &&
                          tmp_path=`echo "$tmp_path" | sed "s=:${2}:=:=g"`
                          # remove surrounding colons
                          tmp_path=`echo "$tmp_path" | sed 's=^:==; s=:$=='`
                          eval export $1="$tmp_path"
                          }
                          function append_to() {
                          remove_from "$1" "$2" # clean the path contents
                          eval export $1="$${1}:$2"
                          }
                          function prepend_to() {
                          remove_from "$1" "$2" # clean the path contents
                          eval export $1="${2}:$$1"
                          }






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Apr 16 '15 at 20:26









                          Greg TarsaGreg Tarsa

                          3792 silver badges7 bronze badges




                          3792 silver badges7 bronze badges


























                              2















                              Below are revised code from Greg Tarsa's solution. Only bash build-in commands are used here. Thus, it will save a lots of fork() system calls.



                              # Calling example:
                              # append_to PATH "/usr/local/bin"

                              function remove_from()
                              {
                              local path="${1}"
                              local dir="${2}"
                              local -a dirs=()
                              local old_ifs="${IFS}"
                              IFS=":"
                              set -- ${!path}
                              while [ "$#" -gt "0" ]
                              do
                              [ "${1}" != "${dir}" ] && dirs+=("${1}")
                              shift
                              done
                              eval "export ${path}="${dirs[*]}""
                              IFS="${old_ifs}"
                              }

                              function append_to()
                              {
                              remove_from "${1}" "${2}"
                              [ -d "${2}" ] || return
                              if [ -n "${!1}" ]
                              then
                              eval "export ${1}="${!1}:${2}""
                              else
                              eval "export ${1}="${2}""
                              fi
                              }

                              function prepend_to()
                              {
                              remove_from "${1}" "${2}"
                              [ -d "${2}" ] || return
                              if [ -n "${!1}" ]
                              then
                              eval "export ${1}="${2}:${!1}""
                              else
                              eval "export ${1}="${2}""
                              fi
                              }





                              share|improve this answer
































                                2















                                Below are revised code from Greg Tarsa's solution. Only bash build-in commands are used here. Thus, it will save a lots of fork() system calls.



                                # Calling example:
                                # append_to PATH "/usr/local/bin"

                                function remove_from()
                                {
                                local path="${1}"
                                local dir="${2}"
                                local -a dirs=()
                                local old_ifs="${IFS}"
                                IFS=":"
                                set -- ${!path}
                                while [ "$#" -gt "0" ]
                                do
                                [ "${1}" != "${dir}" ] && dirs+=("${1}")
                                shift
                                done
                                eval "export ${path}="${dirs[*]}""
                                IFS="${old_ifs}"
                                }

                                function append_to()
                                {
                                remove_from "${1}" "${2}"
                                [ -d "${2}" ] || return
                                if [ -n "${!1}" ]
                                then
                                eval "export ${1}="${!1}:${2}""
                                else
                                eval "export ${1}="${2}""
                                fi
                                }

                                function prepend_to()
                                {
                                remove_from "${1}" "${2}"
                                [ -d "${2}" ] || return
                                if [ -n "${!1}" ]
                                then
                                eval "export ${1}="${2}:${!1}""
                                else
                                eval "export ${1}="${2}""
                                fi
                                }





                                share|improve this answer






























                                  2














                                  2










                                  2









                                  Below are revised code from Greg Tarsa's solution. Only bash build-in commands are used here. Thus, it will save a lots of fork() system calls.



                                  # Calling example:
                                  # append_to PATH "/usr/local/bin"

                                  function remove_from()
                                  {
                                  local path="${1}"
                                  local dir="${2}"
                                  local -a dirs=()
                                  local old_ifs="${IFS}"
                                  IFS=":"
                                  set -- ${!path}
                                  while [ "$#" -gt "0" ]
                                  do
                                  [ "${1}" != "${dir}" ] && dirs+=("${1}")
                                  shift
                                  done
                                  eval "export ${path}="${dirs[*]}""
                                  IFS="${old_ifs}"
                                  }

                                  function append_to()
                                  {
                                  remove_from "${1}" "${2}"
                                  [ -d "${2}" ] || return
                                  if [ -n "${!1}" ]
                                  then
                                  eval "export ${1}="${!1}:${2}""
                                  else
                                  eval "export ${1}="${2}""
                                  fi
                                  }

                                  function prepend_to()
                                  {
                                  remove_from "${1}" "${2}"
                                  [ -d "${2}" ] || return
                                  if [ -n "${!1}" ]
                                  then
                                  eval "export ${1}="${2}:${!1}""
                                  else
                                  eval "export ${1}="${2}""
                                  fi
                                  }





                                  share|improve this answer















                                  Below are revised code from Greg Tarsa's solution. Only bash build-in commands are used here. Thus, it will save a lots of fork() system calls.



                                  # Calling example:
                                  # append_to PATH "/usr/local/bin"

                                  function remove_from()
                                  {
                                  local path="${1}"
                                  local dir="${2}"
                                  local -a dirs=()
                                  local old_ifs="${IFS}"
                                  IFS=":"
                                  set -- ${!path}
                                  while [ "$#" -gt "0" ]
                                  do
                                  [ "${1}" != "${dir}" ] && dirs+=("${1}")
                                  shift
                                  done
                                  eval "export ${path}="${dirs[*]}""
                                  IFS="${old_ifs}"
                                  }

                                  function append_to()
                                  {
                                  remove_from "${1}" "${2}"
                                  [ -d "${2}" ] || return
                                  if [ -n "${!1}" ]
                                  then
                                  eval "export ${1}="${!1}:${2}""
                                  else
                                  eval "export ${1}="${2}""
                                  fi
                                  }

                                  function prepend_to()
                                  {
                                  remove_from "${1}" "${2}"
                                  [ -d "${2}" ] || return
                                  if [ -n "${!1}" ]
                                  then
                                  eval "export ${1}="${2}:${!1}""
                                  else
                                  eval "export ${1}="${2}""
                                  fi
                                  }






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Nov 2 '18 at 7:04

























                                  answered Nov 2 '18 at 6:56









                                  Jie GongJie Gong

                                  212 bronze badges




                                  212 bronze badges


























                                      1















                                      To complete/improve the accepted answer from Tushar, you can:




                                      • avoid having to escape the slashes in the PATH by using non-slash delimiters

                                      • omit the -e option, as per the sed man page: "If no -e, --expression, -f, or --file option is given, then the first non-option argument is taken as the sed script to interpret."

                                      • use the g (global) flag to remove all occurrences


                                      In the end, it gives something like this:



                                      PATH=$(echo "$PATH" | sed 's@:/home/wrong/dir$@@g')





                                      share|improve this answer






























                                        1















                                        To complete/improve the accepted answer from Tushar, you can:




                                        • avoid having to escape the slashes in the PATH by using non-slash delimiters

                                        • omit the -e option, as per the sed man page: "If no -e, --expression, -f, or --file option is given, then the first non-option argument is taken as the sed script to interpret."

                                        • use the g (global) flag to remove all occurrences


                                        In the end, it gives something like this:



                                        PATH=$(echo "$PATH" | sed 's@:/home/wrong/dir$@@g')





                                        share|improve this answer




























                                          1














                                          1










                                          1









                                          To complete/improve the accepted answer from Tushar, you can:




                                          • avoid having to escape the slashes in the PATH by using non-slash delimiters

                                          • omit the -e option, as per the sed man page: "If no -e, --expression, -f, or --file option is given, then the first non-option argument is taken as the sed script to interpret."

                                          • use the g (global) flag to remove all occurrences


                                          In the end, it gives something like this:



                                          PATH=$(echo "$PATH" | sed 's@:/home/wrong/dir$@@g')





                                          share|improve this answer













                                          To complete/improve the accepted answer from Tushar, you can:




                                          • avoid having to escape the slashes in the PATH by using non-slash delimiters

                                          • omit the -e option, as per the sed man page: "If no -e, --expression, -f, or --file option is given, then the first non-option argument is taken as the sed script to interpret."

                                          • use the g (global) flag to remove all occurrences


                                          In the end, it gives something like this:



                                          PATH=$(echo "$PATH" | sed 's@:/home/wrong/dir$@@g')






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Nov 24 '14 at 10:54









                                          Bruno A.Bruno A.

                                          1111 bronze badge




                                          1111 bronze badge


























                                              1















                                              Much simpler one liner.




                                              export PATH=`echo $PATH | tr ":" "n" | grep -v "anaconda" | tr "n" ":"`







                                              share|improve this answer






























                                                1















                                                Much simpler one liner.




                                                export PATH=`echo $PATH | tr ":" "n" | grep -v "anaconda" | tr "n" ":"`







                                                share|improve this answer




























                                                  1














                                                  1










                                                  1









                                                  Much simpler one liner.




                                                  export PATH=`echo $PATH | tr ":" "n" | grep -v "anaconda" | tr "n" ":"`







                                                  share|improve this answer













                                                  Much simpler one liner.




                                                  export PATH=`echo $PATH | tr ":" "n" | grep -v "anaconda" | tr "n" ":"`








                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Jan 22 at 19:58









                                                  user332870user332870

                                                  111 bronze badge




                                                  111 bronze badge


























                                                      0















                                                      The current answers don't solve my similar problem in that I need to remove multiple paths. All these paths are sub-directories of a single directory. In that case, this one-liner works for me: (suppose the pattern is cygwin, i.e., removing all paths that contains cygwin)



                                                      pattern=cygwin; export PATH=$(echo $PATH|tr ':' 'n'|sed "#${pattern}#d" |tr 'n' ':')





                                                      share|improve this answer






























                                                        0















                                                        The current answers don't solve my similar problem in that I need to remove multiple paths. All these paths are sub-directories of a single directory. In that case, this one-liner works for me: (suppose the pattern is cygwin, i.e., removing all paths that contains cygwin)



                                                        pattern=cygwin; export PATH=$(echo $PATH|tr ':' 'n'|sed "#${pattern}#d" |tr 'n' ':')





                                                        share|improve this answer




























                                                          0














                                                          0










                                                          0









                                                          The current answers don't solve my similar problem in that I need to remove multiple paths. All these paths are sub-directories of a single directory. In that case, this one-liner works for me: (suppose the pattern is cygwin, i.e., removing all paths that contains cygwin)



                                                          pattern=cygwin; export PATH=$(echo $PATH|tr ':' 'n'|sed "#${pattern}#d" |tr 'n' ':')





                                                          share|improve this answer













                                                          The current answers don't solve my similar problem in that I need to remove multiple paths. All these paths are sub-directories of a single directory. In that case, this one-liner works for me: (suppose the pattern is cygwin, i.e., removing all paths that contains cygwin)



                                                          pattern=cygwin; export PATH=$(echo $PATH|tr ':' 'n'|sed "#${pattern}#d" |tr 'n' ':')






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Sep 7 '18 at 21:07









                                                          Penghe GengPenghe Geng

                                                          1164 bronze badges




                                                          1164 bronze badges

































                                                              draft saved

                                                              draft discarded




















































                                                              Thanks for contributing an answer to Unix & Linux Stack Exchange!


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid



                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                              To learn more, see our tips on writing great answers.




                                                              draft saved


                                                              draft discarded














                                                              StackExchange.ready(
                                                              function () {
                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f108873%2fremoving-a-directory-from-path%23new-answer', 'question_page');
                                                              }
                                                              );

                                                              Post as a guest















                                                              Required, but never shown





















































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown

































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown







                                                              Popular posts from this blog

                                                              Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

                                                              Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

                                                              Nicolae Petrescu-Găină Cuprins Biografie | Opera | In memoriam | Varia | Controverse, incertitudini...