SoFunction
Updated on 2025-03-10

Detailed explanation of Shell PATH variable usage

As we mentioned in the previous chapter, if a program script wants to run in Linux, it is necessary to use an absolute or relative path to specify the location of the script. But why are the system commands executed directly without specifying paths? For example, the ls command does not enter "/bin/ls" to execute, but directly executes the "ls" command. This is the function of the PATH environment variable.

First check the value of the PATH environment variable, as follows:

[root@localhost ~]# echo $PATH
/usr/lib/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/
bin:/root/bin

The value of the PATH variable is a path separated by ":", which are the paths used by the system to find the command. In other words, we entered a program name. If there is no write path, the system will go to the path defined by the PATH variable to find whether there is a program that can be executed. If it is found, it will be executed, otherwise an error of "the command is not found".

So, can we copy the script we wrote into the path defined by the PATH variable and execute it directly without entering the path? Of course it is OK. Let's try it, let's take the first one as an example.

[root@localhost ~]# cp /root/sh/ /bin/
#Copy to /bin/ directory[root@localhost ~]# 

# Can be executed directly

We just need to copy the program script to any path defined by the PATH variable, such as the /bin/ directory, and the script can be executed directly in the future without specifying an absolute or relative path.

If we put all the program scripts we wrote in the /bin/ directory, we sometimes don’t know the system commands and the programs we wrote (in fact, I am very opposed to changing the structure of the system directory). Can we modify the value of the PATH variable without copying the program script into the /bin/ directory?

Of course, it can be achieved through the superposition of variables.

[root@localhost ~]# PATH="$PATH":/root/sh
#After the variable PATH, add the /root/sh directory[root@localhost ~]# echo $PATH
/usr/lib/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/
bin:/root/bin:/root/sh
#QueryPATHValue of,Variable overlay takes effect

Of course, the PATH variable defined in this way can only take effect temporarily and will disappear once the system is restarted or cancelled. If you want to take effect permanently, you need to write the environment variable configuration file, which we will introduce in detail in the subsequent chapters.

This is the end of this article about the detailed explanation of the usage of Shell PATH variables. For more related Shell PATH variables, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!