≡ Menu

How to check if a command exists in the PATH variable?

The question – I want to check if a command exists in the $PATH variable on my Linux box. If it is not present, I would like to add it. How do I check if my program is already present in the $PATH variable?

The PATH variable on Linux is the place where you specify directories from which you will frequently execute commands. So instead of /bin/ps you can just type ps and Linux will find it in the path and execute /bin/ps.

To check which directories exist in the PATH variable, use the following command:

echo $PATH

This will output something like the following:

[root@server ~]# echo $PATH;
/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
[root@server ~]#

So, as we expected, the /bin directory from which the command ps is run, is there in the PATH variable!

Now the PATH variable can get very messy as one keeps adding directories to it. Having a directory multiple times is not a problem, but should be avoided.

How to check if a command is present in the PATH variable?

The command to do this is called which.

which ps

This will output the physical location of the ps command on the file system, if it is present on the PATH variable.

[root@server ~]# which ps
/bin/ps
[root@server ~]#

The command which searches the locations in the PATH variable and outputs the full absolute path to the command executable file on the Linux file system. The process by which it searches the PATH variable is the same as that used by the bash shell.

If the command cannot be found in the locations in the PATH environment variable, which will output something like the following:

[root@server ~]# which speed
/usr/bin/which: no speed in (/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin)
[root@server ~]#

Comments on this entry are closed.