Locate files using which command in Linux [Cheat Sheet]

Introduction to which command

which command is used to locate the executable file associated with the specified command in Unix-based operating systems. It searches for the executables in the directories listed in the environment variable PATH using the same algorithm as bash.

 

Syntax to use command

The syntax for the which command is:

Advertisement
$ which [options] programname

You can check the directories of your environment variable $PATH using the echo command.

$ echo $PATH

Sample Output:

golinux@ubuntu-PC:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/golinux/hadoop/sbin:/home/golinux/hadoop/bin:/home/hduser/spark/bin:/home/hduser/spark/sbin

Each path is separated with colons : in the output. which command searches for executables in the above directories.

 

Different examples to use which command

1. Show the full path of commands

which command prints the full path of the specified command. The following command returns the full path of grep command.

$ which grep

Sample Output:

which command to show full the path of command

 

2. Print all matching executables in PATH

If there are multiple matching executables in the directories listed in the PATH variable, which only prints the first one. You can use the -a flag to print all matches found in the path.

Advertisement
$ which -a grep

Sample Output:

which command to print all matching executables

 

3. Find the path of multiple commands

which command also accepts multiple arguments. You can specify multiple commands to print their full pathnames. The following command finds the full path of the top, apt, netstat, and useradd commands.

$ which top apt netstat useradd

Sample Output:

which command to find path of multiple commands

 

4. Find the path of which command

You can use which command to find the full path of the which command itself.

$ which which

Sample Output:

which command to find the path of which command

 

Conclusion

which command is useful for finding the full path of executable commands in the terminal. If you still have any confusion, please let us know in the comment section.

Advertisement

 

What’s Next

How to get script name, script path within the bash script in Linux
How to properly check if file exists in Bash or Shell (with examples)

 

Further Reading

man page for which command

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X