Modifying the PATH

Learn how to modify the PATH variable in a shell session.

Appending and prepending

As we learned in the earlier lessons, the PATH environment variable determines where the shell looks for executable programs. We may want to add additional directories to the list.

One common approach is to create a local bin folder in the home directory to hold executable scripts we create ourselves. This way, we don’t have to move executable scripts to a directory like /usr/local/bin.

When modifying the PATH variable, we usually want to append or prepend a directory to the list. Rather than setting the entire PATH value, we use the existing value. Let’s add the following line to the ~/.bashrc file to prepend the ~/bin directory to the PATH variable’s value:

export PATH="~/bin:$PATH"

We use double quotes around the value to ensure that any spaces in existing path names are preserved.

A colon separates each directory in the PATH value. In this case, we put ~/bin first, followed by a colon, followed by the current value of PATH.

When we execute commands, the shell searches through directories in the PATH variable one at a time, executing the first command it finds. By prepending ~/bin, it’s now possible to add our own commands in the ~/bin directory that override any built-in commands.

Let’s try it out. First, we save the file with Ctrl+o, followed by “Enter.” The settings we added to this file won’t be applied to the current shell session, and we want to keep the text editor open since we’re not done changing this file yet. We want to open a new shell session instead.

In the new session, we create the ~/bin directory:

$ mkdir ~/bin

Now, we create a new executable script in that directory. In Locating Executables with PATH, we created a simple greetings script which we copied to /usr/local/bin. Let’s create a new version of that script that displays a different message:

$ cat << 'EOF' > ~/bin/greetings
> #!/usr/bin/env bash
> echo Hi there
> EOF

Executable scripts

Let’s make the new script executable:

$ chmod +x ~/bin/greetings

We use the which command to verify that we’re using the new file:

$ which greetings

Because the ~/bin directory is the first entry in PATH, this will be the command executed rather than the one in /usr/local/bin:

$ greetings

Run the complete code on the terminal below for practice.

cat << "EOF" > /.bashrc
# START:return
[ -z "$PS1" ] && return
# END:return

# START:histcontrol
HISTCONTROL=ignoreboth
# END:histcontrol

# START:histappend
shopt -s histappend
# END:histappend

# START:histsize
HISTSIZE=1000
HISTFILESIZE=2000
# END:histsize

# START:histignore
HISTIGNORE="exit:clear"
# END:histignore

# START:editor
export EDITOR=nano
export VISUAL=nano
# END:editor

# START:path
export PATH="/bin:$PATH"
# END:path
EOF
mkdir /bin
cat << 'EOF' > /bin/greetings 
#!/usr/bin/env bash
echo Hi there
EOF
chmod +x /bin/greetings
which greetings
greetings

Get hands-on with 1400+ tech skills courses.