- Which Command in Linux [Explained with Examples]
- Linux which command examples
- Using which command with multiple executable files
- Display all pathnames with which command
- Exit status of which command
- Comando which no linux
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- Linux which command
- Description
- Syntax
- Options
- Exit status
- Examples
- Related commands
- How to Use the which Command in Linux
- Linux which Command Syntax and Options
- Linux which Command Examples
- 1. Display the Path of Any Executable File
- 2. Display Multiple Paths of Executable Files
- 3. List All Instances
- 4. Find Symbolic Links
- 5. Exclude Shell Built-ins
- Команда which в Linux [с примерами]
- Linux, Примеры команды which
- Использование команды which с несколькими исполняемыми файлами
- Показать все пути с командой which
- Статус вывода команды which
Which Command in Linux [Explained with Examples]
Linux which command is an extremely useful command for locating executable files located anywhere in the Linux system. Learn how to use it.
If you are wondering where exactly is a certain program is located, simply use which on it. The which command locates an executable file in your shell’s search path.
This Linux command has a simple syntax:
Let’s see how to use this simple but useful command.
Linux which command examples
Let’s say you want to know where is the Java executable, use which command:
The output could be like this:
Note that which only works on executable files. So you should use it only with the argument that you can run. For example, you install Java through the JDK package but you don’t run a command called ‘jdk’, you run ‘java’. So you use which command on java, not jdk.
If the which command doesn’t find the executable in the current path, it returns nothing.
Using which command with multiple executable files
You can provide more than one argument to which command:
which man java python nada
[email protected]:~$ which man java python nada /usr/bin/man /usr/bin/java /usr/bin/python
Did you notice something here? I gave it four arguments but the result is displayed for three of them only. It’s because ‘nada’ is not an executable. There is no output for that.
Display all pathnames with which command
The which command in Linux has only one option, -a. By default, which command prints only one pathname for its arguments.
If a program has executable in two places, say in /usr/bin/program and in /usr/local/bin/program, you can display both pathnames using the -a option.
Exit status of which command
If you use which command in a bash script, you may need to know its exit status.
Which command has the following exit status:
- 0 – all arguments are found and executable
- 1 – one or more arguments is nonexistent or non-executable
- 2 – if an invalid option is specified
That’s all you need to know about which command in Linux. If you have questions or suggestions, do let me know in the comments below.
Comando which no linux
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
Linux which command
On Unix-like operating systems, the which command locates the executable file associated with a given command.
This page covers the Linux version of which.
Description
which returns the pathnames of the files (or links) which would be executed in the current environment, had the filename (or filenames) been given as a command (or commands) in a strictly POSIX-conformant shell. It does this by searching the paths in the PATH environment variable for executable files matching the names of the arguments.
which does not follow symbolic links.
Syntax
Options
Exit status
which returns the following value, depending on what occurred:
0 | All filenames were found, and all were executable. |
1 | One or more filenames were not found, or were not executable. |
2 | An invalid option was specified. |
Examples
Locates the pathname of the file which would run if the sh command were executed. On most systems, this will output:
Related commands
find — Find files within a directory hierarchy.
whereis — Locate the binary, source, and manual page files for a command.
How to Use the which Command in Linux
The which command allows users to search the list of paths in the $PATH environment variable and outputs the full path of the command specified as an argument. The command works by locating the executable file matching the given command.
In this tutorial, you will learn to use the which command.
Linux which Command Syntax and Options
The syntax for the which command is:
The [argument] variable specifies the command or commands you want to find.
For example, the following command outputs the location of the cat command:
The which command has only one option, -a . It is optional and used to print all the matches it finds.
The command searches for matches from left to right. If there are multiple matches found in the directories listed in $PATH , which prints only the first one. The -a option instructs which to print all the matches.
Important: On many Linux distributions, which excludes the shell built-in commands and does not output their location.
Having multiple matches sometimes means one match is a symlink to the other. However, it is possible to have two versions of the same command in different locations or two different commands using the same name.
Note: Unlike many other commands, which has no —help option. To see the command description and help, run man which .
Exit Status
The which command returns one of the following values that indicate its exit status:
- 0 . All arguments were found and executable.
- 1 . One or more arguments don’t exist or aren’t executable.
- 2 . An invalid option has been specified.
Linux which Command Examples
The following examples showcase how the which command works and how to use the available option.
1. Display the Path of Any Executable File
To display the path of any command, pass the command name as an argument after which .
The output shows the path to the tr command executable file, located in /usr/bin/tr.
2. Display Multiple Paths of Executable Files
which accepts multiple arguments and outputs the path to each one in the specified order.
The command works through the supplied list and outputs the results for the nc command, mount command, and sort command, separating each result with a newline character.
3. List All Instances
which only shows the first match it finds in the $PATH variable directory list. Use the -a option to show every match for the specified command.
For example, searching for instances of the less command outputs two results when using the -a option:
Use the ls command to check file details and determine if both versions are executable files. Run:
ls -lh /usr/bin/less ls -lh /bin/less
The output shows two identical versions of the same command in two locations, both 176 KB large, and both executable.
Note: The /bin directory contains executables that can be used by the system administrator and any other user, and which are required for emergency system repairs. The /usr/bin directory is the primary directory for executable commands on the system.
4. Find Symbolic Links
Using the -a option lists all the paths containing an instance of the specified program. While multiple versions of the same program can exist on a system, sometimes one of the instances is only a symbolic link and not a binary file.
For example, running the following command outputs two instances of the atq command:
Again, use the ls command to check the details for both files. Run:
ls -lh /usr/bin/atq ls -lh /bin/atq
The output shows that both files are symbolic links ( -> ) only 2 bytes large and pointing to the at command.
5. Exclude Shell Built-ins
As previously mentioned, the which command excludes shell built-ins from its output.
For example, asking for the location of the read and man commands only outputs the location for the man command executable file, as read is a bash shell command.
This tutorial showed how to use the which command in Linux to find the path to a command’s executable binary. See and download our Linux commands cheat sheet for other essential Linux commands and examples of using them.
Команда which в Linux [с примерами]
Добавить в избранное
К оманда which в Linux используется для поиска любой команды в Linux. Команда — это исполняемый файл, который вы можете запустить. Команда which находит исполняемый файл в пути поиска вашей оболочки.
Другими словами, если вам интересно, где именно находится определенная программа, просто используйте which. Команда Linux имеет простой синтаксис:
Давайте посмотрим, как использовать эту простую, но полезную команду.
Linux, Примеры команды which
Допустим, вы хотите знать, где находится исполняемый файл Java, используйте команду:
destroyer@andreyex:~$ which java
/usr/bin/java
Обратите внимание, что работает только с исполняемыми файлами. Таким образом, вы должны использовать which только с аргументом. Например, вы устанавливаете Java с помощью пакета JDK, но не запускаете команду с именем «jdk», вы запускаете «java». Таким образом, вы используете команду which на Java, а не JDK.
Если команда which не находит исполняемый файл в текущем пути, она ничего не возвращает.
Использование команды which с несколькими исполняемыми файлами
Вы можете предоставить более одного аргумента для команды which:
which man java python nada
destroyer@andreyex:~$ which man java python nada
/usr/bin/man
/usr/bin/java
/usr/bin/python
Вы заметили что-то здесь? Мы дали ему четыре аргумента, но результат отображается только для трех из них. Это потому, что «nada» не исполняемый файл. Там нет вывода для which.
Показать все пути с командой which
Команда which в Linux имеет только одну опцию -a. По умолчанию эта команда печатает только один путь для своих аргументов.
Если программа имеет исполняемый файл в двух местах, например, в /usr/bin/program и в /usr/local/bin/program, вы можете отобразить оба пути с помощью опции -a.
Статус вывода команды which
Если вы используете команду which в скрипте bash, вам может потребоваться узнать ее состояние завершения.
Команда which имеет следующий статус выхода:
- 0 — все аргументы найдены и выполняются
- 1 — один или несколько аргументов не существуют или не выполняются
- 2 — если указан неверный параметр
Это все, что вам нужно знать о команде which в Linux. Если у вас есть вопросы или предложения, дайте нам знать в комментариях ниже.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.