- Если не получается найти командами ниже – надо использовать find 🙂
type – считаю является самой первой командой, которой нужно на мой взгляд пользоваться для поиска исполняемого файла/понимания того, что исполняется. Type показывает какого типа является исполняемая команда – встроенная в shell функция (shell builtin), внешняя функция (shell function) или утилита. Для последних показывается путь до утилиты.
#type echo
echo is a shell builtin
#type ping
ping is /sbin/ping
#type uname
uname is /usr/bin/uname
#hello_world() { ;\
echo "Hello_World" ;\
}
#
#type hello_world
hello_world is a shell function
realpath – показывает абсолютный путь до указанного файла
root@server:~# realpath debug
/root/debug
whereis – поиск пути до исполняемого файла/source code/man в директориях по пути PATH. По умолчантю ищет бинарные файлы, исходные и man для команды, можно отдельно искать через соответствующие опции -b -s -m. Недостаток – команда не говорит о том, какой из файлов (при наличии нескольких) исполняется по факту при запуске.
which – which и whereis не полные эквиваленты. Which так же как и whereis, ищет исполняемые файлы в директориях PATH, но which по умолчанию упоказывает первый match для поиска, а не все hits (т.е. путь к файлк, которяй запускается по команде); так же он ищет exact match в отличии от whereis (whereis – vim.tiny = vim, which – vim.tiny != vim). При этом с which можно посмотреть и все math добавив флаг -a.
Вот пример для Ruby поставленного через rvm.
[tool@sv]$ which ruby /usr/local/rvm/rubies/ruby-2.1.4/bin/ruby [tool@sv]$ whereis ruby ruby: /usr/bin/ruby /usr/lib/ruby /usr/lib64/ruby /usr/share/man/man1/ruby.1.gz
locate – делает быстрый поиск файла во всей системе, но использует для этого внутреннюю базу/кеш (/var/cache/locate/locatedb), в итоге результат можно получить быстро, но за счет предварительного создания этой базы (под капотом использует find, запускается sudo updatedb, обычно раз в сутки по cron). Для разовых задач считаю избыточная утилита, проще использовать find.
questions
Which program updates the database that is used by the locate command?
updatedb
When piping the output of find to the xargs command, what option to find is useful if the filenames have spaces in them?
A. –rep-space
B. –print0
C. –nospace
D. –ignore-space
Answer: B
This option to the find command is useful if the filenames contain spaces when redirecting the output of find to the xargs command. The syntax of the option is:
find [where to start searching from] [expression determines what to find] -print0 The -print0 option tells the find command to print the full file name on the standard output, followed by a null character (ASCII code 0) instead of the newline character. This allows file names that contain spaces or other special characters to be correctly interpreted by the xargs command, which can use the -0 option to read items from the standard input that are terminated by a null character. The syntax of the xargs command with the -0 option is:
xargs -0 [command]
The -0 option tells the xargs command to expect the items from the standard input to be separated by a null character, and to execute the command using the items as arguments.
Therefore, the command find ... -print0 | xargs -0 ... will search for files and directories using the find command, print the results with a null character as the separator, pipe the output to the xargs command, which will read the items with a null character as the separator, and execute another command using the items as arguments. This will avoid any problems with filenames that contain spaces or other special characters.
The other options are incorrect for the following reasons: These options does not exists in the find command.
Questions
Which of the following commands shows the definition of a given shell command?
A. where
B. stat
C. type
D. case
Answer: C
Which of the following commands can be used to search for the executable file foo when it has been placed in a directory not included in $PATH?
A. apropos
B. which
C. find
D. query
E. whereis
Answer: C Explanation: In Linux, when a command is entered in the terminal, the shell searches for the executable file in a set of directories specified in the environment variable $PATH. If the executable is not found in any of those directories, then the command will fail. However, it's possible that an executable file may be located in a directory that is not included in $PATH. In this case, we can use the find command to search for the file. The find command is used to search for files and directories in a given directory hierarchy. It can search for files based on various criteria, such as name, type, size, and date modified. To use find to search for an executable file named foo in a specific directory, we can use the following command: find /path/to/directory -name foo -type f -perm /a+x Here, /path/to/directory is the path to the directory where we want to search for the file foo. The -name option specifies the name of the file we want to find, and the -type f option specifies that we are searching for a regular file. The -perm /a+x option specifies that we are searching for a file that is executable by anyone. Once find locates the file, we can run it by specifying its full path in the command line, for example: /path/to/directory/foo Alternatively, we can add the directory containing the file to $PATH, so that we can run the file without specifying its full path each time. However, this may not always be desirable, especially if the file is located in a directory that is not meant to be used for general system-wide executables. In such cases, using find to locate the file is a more secure and controlled approach.