Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the most elegant way to remove a path from the $PATH variable in Bash?
    primarykey
    data
    text
    <p>Or more generally, how do I remove an item from a colon-separated list in a Bash environment variable?</p> <p>I thought I had seen a simple way to do this years ago, using the more advanced forms of Bash variable expansion, but if so I've lost track of it. A quick search of Google turned up surprisingly few relevant results and none that I would call "simple" or "elegant". For example, two methods using sed and awk, respectively:</p> <pre><code>PATH=$(echo $PATH | sed -e 's;:\?/home/user/bin;;' -e 's;/home/user/bin:\?;;') PATH=!(awk -F: '{for(i=1;i&lt;=NF;i++){if(!($i in a)){a[$i];printf s$i;s=":"}}}'&lt;&lt;&lt;$PATH) </code></pre> <p>Does nothing straightforward exist? Is there anything analogous to a split() function in Bash?</p> <p><strong>Update:</strong><br/> It looks like I need to apologize for my intentionally-vague question; I was less interested in solving a specific use-case than in provoking good discussion. Fortunately, I got it!</p> <p>There are some very clever techniques here. In the end, I've added the following three functions to my toolbox. The magic happens in path_remove, which is based largely on Martin York's clever use of <code>awk</code>'s RS variable.</p> <pre><code>path_append () { path_remove $1; export PATH="$PATH:$1"; } path_prepend () { path_remove $1; export PATH="$1:$PATH"; } path_remove () { export PATH=`echo -n $PATH | awk -v RS=: -v ORS=: '$0 != "'$1'"' | sed 's/:$//'`; } </code></pre> <p>The only real cruft in there is the use of <code>sed</code> to remove the trailing colon. Considering how straightforward the rest of Martin's solution is, though, I'm quite willing to live with it!</p> <hr> <p>Related question: <A href="https://stackoverflow.com/questions/273909/how-do-i-manipulate-path-elements-in-shell-scripts"><a href="https://stackoverflow.com/questions/273909/how-do-i-manipulate-path-elements-in-shell-scripts">How do I manipulate $PATH elements in shell scripts?</a></A></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload