Understanding the PATH Variable in Bash

Environment variables track specific system information, such as the name of the user logged into the shell, the default home directory for the user, the search path the shell uses to find executable programs, and so on.

The PATH environment variable in Bash and other Unix-like operating systems such as Linux and macOS is a critical variable that dictates where the shell looks for executable files. When you type a command in the terminal, the shell searches through the directories listed in the PATH variable, in the order they are listed, to find the executable file that matches the command.

The directories in the PATH variable are separated by colons (:). You can view your current PATH setting by running the following command:

echo $PATH

How it Works

For example, suppose PATH is set as follows:

When you run a command like ls, the shell will look for the ls executable in the following directories, in this order:

  1. /usr/local/bin/

  2. /usr/bin/

  3. /user/local/sbin/

If it finds ls in /usr/bin/, for instance, it will run it from there and won't search in /user/local/sbin/.

Workshop Exercises

Exercise 1: Understand PATH Priority

  1. Open a terminal.

  2. Type which ls and press Enter.

  3. The output shows the absolute path of the ls command. As we can see, this directory is the second one listed in the PATH directory.

Exercise 2: Add a Directory to PATH

Create a directory ~/scripts where you keep some of your custom scripts. To add this directory to your PATH as follows:

  1. Open a terminal.

  2. Run export PATH=$PATH:~/my_scripts

  3. Confirm by running echo $PATH.

Note: This change is temporary and will be lost when you close the terminal. To make it permanent, you'll have to add the export command to your shell's startup file, like .bashrc or .bash_profile.

Exercise 3: Create a Custom Command

  1. Create a new script file in the ~/scripts directory.

     touch ~/scripts/test_command.sh
  2. Make it executable.

     chmod +x ~/scripts/test_command.sh

  3. Edit the file to include the following:

     echo "Hello, this is my custom command. Let's check it!"
  4. Save the file.

  5. Try running test_command.sh from anywhere in the terminal. Did it work? If not, make sure that ~/my_scripts is in your PATH.

Exercise 4: Remove a Directory from PATH

  1. Run export PATH=$(echo $PATH | sed 's/:\/home\/centos\/scripts//')

  2. This will remove /home/centos/scripts from your PATH (if it exists).

  3. Confirm by running echo $PATH.