Change Your $PATH Temporarily

Problem

You want to easily add or remove a directory to or from your $PATH for this session only.

Solution

There are several ways to handle this problem.

You can prepend or append the new directory, using PATH="newdir:$PATH" or PATH="$PATH:newdir", though you should make sure the directory isn’t already in the $PATH.

If you need to edit something in the middle of the path, you can echo the path to the screen, then use your terminal’s kill and yank (copy and paste) facility to duplicate it on a new line and edit it. Or, you can add the “Macros that are convenient for shell interaction” from the readline documentation at http://tiswww.tis.case.edu/php/chet/readline/readline.html#SEC12, specifically:

# edit the path
"\C-xp": "PATH=${PATH}\e\C-e\C-a\ef\C-f"
# [...]
# Edit variable on current line.
"\M-\C-v": "\C-a\C-k$\C-y\M-\C-e\C-a\C-y="

Then pressing Ctrl-X P will display the $PATH on the current line for you to edit, while typing any variable name and pressing Meta Ctrl-V will display that variable for editing. Very handy.

For simple cases you can use this quick function (adapted slightly from Red Hat Linux’s /etc/profile):

# cookbook filename: func_pathmunge

# Adapted from Red Hat Linux

function pathmunge {
    if ! echo $PATH | /bin/egrep -q "(^|:)$1($|:)" ; then
        if [ "$2" = "after" ] ; then
            PATH="$PATH:$1"
        else
            PATH="$1:$PATH"
        fi
    fi
}

The egrep pattern looks for the value in $1 between two : or (|) at the beginning (^) or end ($) of the $PATH string. We chose ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.