In most computer systems, there is a variable which defines the order in which, your programs, when executed, are located on the file system.
In this post, I will attempt to explain the PATH variable, which is the variable that defines the location, the operating system shell, searches for the executable programs.
When you open a shell in Linux for example, you are presented with something similar to the infamous “$” prompt for regular users or the pound “#” prompt for administrative/root users. The prompt is simply waiting for you input to execute it. Now, let’s give the prompt a command and see the response, we will then break the actions a part and understand how the PATH variable is involved with the action.
Now, let’s type the following command followed by the ‘Enter’ key:
echo “Hello!”
You should get the following output:
Hello!
The command echo simply tells the shell to get the quoted string and print it. But in reality, the command echo is a separate executable located somewhere in the filesystem. Now let’s type the following command to identify where the command is located on the file system:
which echo
you should get the following output, at least on most systems, the location might vary:
/usr/bin/echo
/usr/bin/echo is the actual location where the executable echo is located. But now, you should ask yourself a question; how did the system knew where the location of echo was? The answer is: the PATH variable.
Now, type the following command and press the ‘Enter’ key:
echo $PATH
You should get an output similar to the following:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
The content of the PATH variable is a string containing a list of directories separated by the “:” character, containing all the directories/folders the shell will search for when you enter a command. When you entered echo “Hello!”, the system starts scanning the PATH variables until the echo executable is found, in this case, the following search order is scanned:
- does the directory /usr/local/sbin contain the echo executable? No
- does the directory /usr/local/bin contain the echo executable? No
- does the directory /usr/sbin contain the echo executable? No
- does the directory /usr/bin contain the echo executable? YES
At this point, the search ends, and /usr/bin/echo “Hello!” command is executed behind the scenes, and the output Hello! is displayed.
There are many more things that happen when a program is executed, but for the simplicity of this post, we will end here.
On Windows there is also a PATH variable, the only difference is the separation character, on Windows the character “;” is used instead.
I hope now you have a better idea of what the PATH variable is and how it’s used.
Thank you for reading this post, and I hope it makes a difference in your UNIX understanding journey. Happy typing…