Linux which search path

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.

Источник

Команда which в Linux

В этом руководстве мы рассмотрим команду Linux which .

Linux, which команда используется для определения местоположения данного исполняемого файла, который выполняется при вводе имени исполняемого файла (команды) в строке терминала. Команда ищет исполняемый файл, указанный в качестве аргумента, в каталогах, перечисленных в переменной среды PATH.

Читайте также:  Comodo browser for linux

Что такое PATH

В Linux PATH — это переменная окружения, которая сообщает оболочке и другим программам, в каких каталогах искать исполняемые файлы. Он состоит из списка разделенных двоеточиями абсолютных путей к каталогам, содержащим исполняемые файлы.

Чтобы просмотреть содержимое переменной PATH, используйте команду echo с $PATH в качестве аргумента:

Результат будет выглядеть примерно так:

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin 

Как использовать команду which

Синтаксис команды which следующий:

Например, чтобы найти полный путь к команде ping , вы должны ввести следующее:

Результат будет примерно таким:

Вы также можете указать несколько аргументов для команды which :

Вывод будет включать полные пути к исполняемым файлам netcat и uptime :

Поиск производится слева направо, а если более одного совпадения найдены в каталогах , перечисленных в PATH переменной пути, which будет печатать только первый. Чтобы распечатать все совпадения, используйте параметр -a :

В выводе будут показаны два полных пути к touch команде :

Обычно один из исполняемых файлов является лишь symlink на другой, но в некоторых случаях у вас могут быть две версии одной и той же команды, установленные в разных местах, или совершенно разные команды с одним и тем же именем.

Выводы

Команда which используется для поиска команды путем поиска исполняемого файла команды в каталогах, указанных переменной окружения PATH .

Если у вас есть вопросы или отзывы, оставьте комментарий ниже.

Источник

Команды 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.

Читайте также:  Alt linux сборка пакетов

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 (143)
  • MySQL (76)
  • PHP (125)
  • React.js (66)
  • SSH (27)
  • Ubuntu (66)
  • Web-разработка (509)
  • WordPress (73)
  • Yii2 (69)
  • БазаДанных (95)
  • Битрикс (66)
  • Блог (29)
  • Верстка (43)
  • ИнтернетМагаз… (84)
  • КаталогТоваров (87)
  • Класс (30)
  • Клиент (27)
  • Ключ (28)
  • Команда (68)
  • Компонент (60)
  • Конфигурация (59)
  • Корзина (32)
  • ЛокальнаяСеть (28)
  • Модуль (34)
  • Навигация (31)
  • Настройка (137)
  • ПанельУправле… (29)
  • Плагин (33)
  • Пользователь (26)
  • Практика (99)
  • Сервер (74)
  • Событие (27)
  • Теория (104)
  • Установка (65)
  • Файл (47)
  • Форма (58)
  • Фреймворк (192)
  • Функция (36)
  • ШаблонСайта (68)

Источник

What is the difference between locate/whereis/which

What is the basic difference between locate whereis and which command. The basic difference that I observed is that locate locates all the related file names in the entire filesystem, whereas whereis and which commands only give the location (system/local address of file) of installed application. How accurate is my observation? How are these commands implemented internally. Why does locate work so fast as compared to the dash search, while locate has to search a particular filename matching the target string in the entire filesystem hierarchy?

Sorry I was just attempting to add onto your question. type is another command that seems (to my eyes) do a similar thing to the ones you mentioned.

@jamesmstone I dont think there is any type command which works in my system. I am unable to find any manual or info page for the type command. I tried man type and info type .

3 Answers 3

which finds the binary executable of the program (if it is in your PATH). man which explains more clearly:

which returns the pathnames of the files (or links) which would be executed in the current environment, had its arguments been given as commands in a strictly POSIX-conformant shell. It does this by searching the PATH for executable files matching the names of the arguments. It does not follow symbolic links.

whereis finds the binary, the source, and the man page files for a program. For example

$ whereis gimp /usr/bin/gimp /usr/lib/gimp /etc/gimp /usr/share/gimp /usr/share/man/man1/gimp.1.gz 

You can get extra detail by passing the output of these commands as arguments to ls -l or file

$ ls -l $(which gimp) lrwxrwxrwx 1 root root 8 Jun 30 19:59 /usr/bin/gimp -> gimp-2.8 $ file $(which gimp) /usr/bin/gimp: symbolic link to gimp-2.8 

locate indeed finds all the files that have the pattern specified anywhere in their paths. You can tell it to only find files and directories whose names (rather than full paths) include the pattern with the -b option, which is usually what you want, and gives a less unwieldy list.

Читайте также:  Linux other user folder

locate is fast because it uses a binary database that gets periodically updated (once daily, by cron ). You can update it yourself to ensure recently added files are found by running sudo updatedb

One more thing about locate — it doesn’t care whether files still exist or not, so to avoid finding recently deleted files, use -e . Often I also pipe to less as the list can be long. Typically I do:

sudo updatedb && locate -b -e gimp | less 

How Unity’s dash works is explained here — it uses Zeitgeist to index system files and learn from usage patterns, and enables other applications to make use of this data, so it is doing a lot more work than locate .

Источник

How can I search a file by its name and partial path?

Often I have a file name and it’s partial path, e.g. «content/docs/file.xml». Is there a simple way to search for that file, without manually cutting into parts its name to provide directory name and file name separately? It’d be great if find worked in that way, so I could run find content/docs/file.xml , but unfortunately it doesn’t.

thanks, @Bob, it’s really worked for me. Btw, interesting, that if I’m adding a slash after an asterisk: «find -path */content/docs/file.xml», it doesn’t work. Thanks a lot anyway.

The reason the slash after asterisk didn’t work is probably because the asterisk should have been escaped, see the edit to my answer.

5 Answers 5

Pass in a * wildcard to indicate a match for anything. You also need to escape the * s, e.g.:

find . -path \*content/docs/file.xml 

or enclose the pattern in quotes, e.g.:

find . -path "*content/docs/file.xml" 

As the man page describes it:

$ find . -name *.c -print

find: paths must precede expression

This happens because *.c has been expanded by the shell resulting in find actually receiving a command line like this:

find . -name bigram.c code.c frcode.c locate.c -print

That command is of course not going to work. Instead of doing things this way, you should enclose the pattern in quotes or escape the wild‐ card:

$ find . -name \*.c -print

Источник

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