Which bash linux команда

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
Читайте также:  Узнать размер дисков linux

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.

Источник

Команды type, which, whereis, whatis и locate

Команда type позволяет выяснить, содержится ли некоторая команда в системе, и определить тип данной команды. Команда также сообщает, является ли название команды действительным и где именно в системе находится эта команда:

$ type echo echo встроена в оболочку $ type ls ls является алиасом для 'ls --color=auto' $ type rm rm является /bin/rm $ type wc wc является /usr/bin/wc

Команда which

Команда which выводит полный путь до команды, если она находится в пути поиска $PATH . Команда which показывает первую найденную команду в переменной $PATH . Если надо проверить существование нескольких совпадений, используется опция -a :

$ which echo /bin/echo $ which ls /bin/ls $ which wc /usr/bin/wc

Команда whereis

Команда whereis позволяет найти не только исполняемые файлы, но и файлы документации и конфигурации. Выполняет поиск в ограниченном количестве каталогов, например в каталогах стандартных двоичных файлов, каталогах библиотек и в каталогах man .

$ whereis awk /usr/bin/awk /usr/share/man/man1/awk.1.gz $ whereis sed /bin/sed /usr/share/man/man1/sed.1.gz /usr/share/info/sed.info.gz

Команда whatis

Команда whatis показывает краткую информацию о команде из ее man-страницы.

$ whatis rm rm (1) - remove files or directories $ whatis awk awk (1) - pattern scanning and text processing language

Команда locate

Команда locate выполняет поиск по базе данных имен файлов, хранящейся в Linux. Для получения актуальных результатов, необходимо регулярно обновлять базу данных со списком имен файлов. Чаще всего ОС настроена таким образом, что обновление будет выполняться автоматически. Если обновление по умолчанию отключено, можно обновить базу данных вручную:

  • -q — позволяет скрыть сообщения об ошибках (например, нет доступа к файлу)
  • -n — позволяет ограничить количество возвращаемых результатов
  • -c — позволяет узнать количество файлов, соответствующих заданному критерию поиска
  • -i — позволяет провести поиск файлов без учета регистра
$ locate .php -n 10 # первые 10 файлов с расширением .php $ locate .html -i # поиск html-файлов без учета регистра

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

  • 1С:Предприятие (31)
  • API (29)
  • Bash (43)
  • CLI (99)
  • CMS (139)
  • CSS (50)
  • Frontend (75)
  • HTML (66)
  • JavaScript (150)
  • Laravel (72)
  • Linux (146)
  • MySQL (76)
  • PHP (125)
  • React.js (66)
  • SSH (27)
  • Ubuntu (68)
  • Web-разработка (509)
  • WordPress (73)
  • Yii2 (69)
  • БазаДанных (95)
  • Битрикс (66)
  • Блог (29)
  • Верстка (43)
  • ИнтернетМагаз… (84)
  • КаталогТоваров (87)
  • Класс (30)
  • Клиент (27)
  • Ключ (28)
  • Команда (68)
  • Компонент (60)
  • Конфигурация (62)
  • Корзина (32)
  • ЛокальнаяСеть (28)
  • Модуль (34)
  • Навигация (31)
  • Настройка (140)
  • ПанельУправле… (29)
  • Плагин (33)
  • Пользователь (26)
  • Практика (99)
  • Сервер (74)
  • Событие (27)
  • Теория (105)
  • Установка (66)
  • Файл (47)
  • Форма (58)
  • Фреймворк (192)
  • Функция (36)
  • ШаблонСайта (68)
Читайте также:  Linux часы и время

Источник

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.

How to use the which command in Linux, with examples.

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:

Find the location of the cat command executable file using which.

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.

List all instances of a command using which.

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 .

Читайте также:  Linux bond balance rr

Find the tr command executable with 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.

Find the paths to multiple commands using which.

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:

Display the path to all instances of a command.

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

Check the details of a command

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.

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:

Find all 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

Finding symbolic links using the ls command.

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.

The which command excluding a shell built-in from its output.

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.

Источник

Оцените статью
Adblock
detector