Cover by Cameron Newham, JP Vossen, Carl Albing

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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 ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required