Which and whereis command in linux

Linux: which vs. whereis

“which” is a very useful command used to find the location of an executable which is in your path e.g.:

I actually didn’t know that there is also a command “whereis” which is kind of similar:

# whereis yacc yacc: /usr/bin/yacc /usr/share/man/man1p/yacc.1p.gz

It doesn’t only return the location of the executable but also of source files and man pages. Another difference is also that it doesn’t search the configured path but looks through an internal list of common Unix paths.

So this basically means that there are executables which will be found by “which” but not by “whereis” because they are in a non-standard directory which is in the path. On the other hand, “whereis” will find other executables not found by which if some of the standard directories are not in the path.

So if you do not find an executable with one of the two commands, you should give the other one a try.

“which” stays my preferred command for this (and I’ll only use “whereis” if which fails to find something) because it’s just returning one full path without anything else which makes it so easy to combine it with other commands e.g.:

# cat `which yacc` #! /bin/sh exec /usr/bin/bison -y "$@"

Of course you can also tell “whereis” to only show binaries and then use awk to get the output you need:

# whereis -b yacc | awk '< print $2; >' /usr/bin/yacc
# cat `whereis -b yacc | awk '< print $2; >'` #! /bin/sh exec /usr/bin/bison -y "$@"

But it’s of course much longer and more complex…

Источник

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

Читайте также:  Vps 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 (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)

Источник

An intro to finding things in Linux

An intro to finding things in Linux

This command will go through your entire filesystem and locate every occurrence of that keyword, so you can image that the results can be overwhelming.

locate uses a database that is usually updated once a day, so if you’re searching for something that was created recently, it might not return in your search. You can use the

command to manually update the locate command’s database.

The whereis command

In Linux, executable files are called binaries, if you want to locate a binary, whereis is more efficient than locate .

This command will return the binaries location, its source and the man page if available

The which command

The PATH variable in Linux holds the directories in which the operating system looks for the commands you execute in the command line.

The which command locates an a binary in your PATH . If it doesn’t find the binary in the current PATH , it returns nothing.

These directories typically include /usr/bin but may include /usr/sbin and a few others.

The find command

The most powerful searching command is the find command. You can use it to search in any designated directory and use a variety of parameters.

find directory options expression

Let’s say I have a file named test.txt and I need to find it but am not sure what exact directory it’s in. I can execute the following to search starting from the top of the file system /

find / -type f -name test.txt

  • / means from the top of the file system
  • -type is what you are looking for, f means file, b means block special device file, c character special device file, d directory, l symbolic link.
  • -name is the name you are looking for, results will match exactly.
Читайте также:  Linux copy all but one file

A search that looks in every directory, starting from the top, can take a while. We can speed things up by providing a directory, let’s say I know this file is in the home directory.

time find /home -type f -name test.txt

I used the time command here so we can see how long each command took.

The find command only displays exact name matches. If file.txt had a different extension, it would not have been returned. I’ve created another file test.conf and now if I search with find only using test.txt as the name, I no longer get the test.conf file returned.

We can work around this limitation by using wildcards . They let us match multiple characters and come in a few different forms:

Let’s say we have a directory with files cat, hat, what, and bat

  • * matches multiple characters *at would match: cat, hat, what, and bat.
  • ? matches a single character ?at would match cat, hat, bat but not what.
  • [] matches character that appear inside the square brackets [c,b] would match cat and bat
find /home -type f -name test.*

find supports plenty of tests and even operators, let’s say we wanted to find all the files with permissions that are not 0600 and the directories that are not 0700.

find ~ \( -type f -not -perm 0600 \) -or \( -type d -not perm 0700 \)

this command says: find all files where permissions are not 0600 or all directories where permissions are not 0700.

  • find ~ look in the ~ directory (home).
  • \( -type f -not -perm 0600) The slash is escaping the parenthesis, we use parenthesis here to group tests and operators together to form a larger expression. By default, find evaluates from left to right. The -not tells us this test is a match if the result is false. -not can be abbreviated with an ! so this part could be \( -type f ! -perm 0600) as well
  • -or This is telling us that if either test is true, it’s a match. Can be abbreviated to -o
  • \( -type d -not perm 0700 \) another test, very similar to the first one, except the type here is directory.

find is a powerful command with many tests, make sure to look into it more.

and that’s it for this intro to finding stuff in Linux 🙂

Читайте также:  Команда распаковки tar gz линукс

Источник

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.

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 .

Источник

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