PATH environment variable

One of the most important environment variables on Linux operating systems is the PATH variable. This variable holds the colon-separated list of directories used to find commands that you enter. For example, if PATH is set to /bin:/usr/sbin and you type echo, Linux looks for an executable program called echo in /bin and then in /usr/sbin.

linux echo path

Here is an example. Let’s say that we have a script named script.sh and we want to execute it. If the script is placed in the folder listed in the PATH variable, we can run the script regardless of the directory we are currently in:

linux executing scripts

In the example above you can see that, although our working directory is /home/bob, we were able to execute a script called script.sh. This is because the script is located in the /bin directory, the directory listed in the PATH variable. But what if we move the script to other directory that is not listed in the PATH variable?

linux command not found

From the output above you can see that, although our working directory is /home/bob, the directory in which the script script.sh is located, we can’t execute it. This is because the system checks for commands only in directories listed in the PATH variable.

Note that we can execute the script located in the /home/bob directory by providing the absoulte or relative path to the script. In the example above we could execute the script by entering ./script.sh (the relative path (./) indicates the working directory) or /home/bob/script.sh (the absolute path):

linux executing scripts using relative and absolute path

Geek University 2022