How to get full path name of a Linux command
I want to find out the file path of commands in Linux e.g., ls has file path as /bin/ls . How can I find out the exact path of some commands?
5 Answers 5
As pointed out, which would do it. You could also try:
This will list all the paths that contains progName . I.e whereis -b gcc on my machine returns:
gcc: /usr/bin/gcc /usr/lib/gcc /usr/bin/X11/gcc
On my machine I have /bin/gcc and /usr/bin/gcc (both of which are links which after many links point to the actual program which is /usr/bin/x86_64-linux-gnu-gcc-9 ), but the former isn’t listed in whereis gcc .
you can use which , it give you path of command:
Well done with the use of type which is generally a builtin, and if not provided by POSIX. type -p (where that option is available) will return a pruned result which can be assigned and used as a command. e.g. myprog=$(type -p someexename) .
You can use the which command. In case of a command in your $PATH it will show you the full path:
mureinik@computer ~ $ which cp /usr/bin/cp
And it will also show details about aliases:
mureinik@computer ~ $ which ls alias ls='ls --color=auto' /usr/bin/ls
Yes you can find it with which command
You did not specify, which shell you are going to use, but I strongly recommend using which , as it does not necessarily do, what you expect. Here two examples, where the result possibly is not what you expect:
(1) Example with bash, and the command echo :
would output /usr/bin/echo , but if you use the echo command in your bash script, /usr/bin/echo is not executed. Instead, the builtin command echo is executed, which is similar, but not identical in behaviour.
(2) Example with zsh, and the command which :
would output the message which: shell built-in command (which is correct, but certainly not a file path, as you requested), while
would output the file path /usr/bin/which , but (as in the bash example) this is not what’s getting executed when you just type which .
There are cases, when you know for sure (because you know your application), that which will produce the right result, but beware that as soon as builtin-commands, aliases and shell functions are involved, you need first to decide how you want to handle those cases, and then choose the appropriate tools depending on the kind of shell which you are using.
Команда which в Linux
В этом руководстве мы рассмотрим команду Linux which .
Linux, which команда используется для определения местоположения данного исполняемого файла, который выполняется при вводе имени исполняемого файла (команды) в строке терминала. Команда ищет исполняемый файл, указанный в качестве аргумента, в каталогах, перечисленных в переменной среды PATH.
Что такое 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 .
Если у вас есть вопросы или отзывы, оставьте комментарий ниже.
Get the Path of a Linux Command
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
1. Overview
A Linux command that we type into a shell can be built-in, a function, an alias, or an external executable. We can find what it is and its path with several Linux utilities such as which, command, type, locate, whatis, and whereis.
In this article, we will explore the which, command, type, and whereis utilities as these are normally found in most Linux-based operating systems.
2. PATH Environment Variable
Before we jump to the explanation of the utilities, we need to know that the application, such as our shell, finds (and executes) the command from a list of directories that are stored in an environment variable called PATH. Each directory is separated with a colon character “:”.
We can show what is inside this variable by calling the echo command:
$ echo $PATH /home/baeldung/.cargo/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/snap/bin
This means that when we install a program or application on our system, to be able to call the executable from any directory from our shell, we need to ensure that the PATH variable has the path of the executable.
We can update the PATH variable temporarily by running this command:
$ export PATH=$PATH:/sampledir/path $ echo $PATH /home/baeldung/.cargo/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/snap/bin:/sampledir/path
The PATH will be reset on reboot.
However, we can update the PATH variable permanently by updating the .bashrc file:
export PATH=$PATH:/sampledir/path
3. which Command
Most Linux-based operating systems have the which command installed. We can use this command to get the path of a Linux command:
$ which docker /usr/bin/docker
This shows that when we call the docker command, it will run the Docker executable file in the /usr/bin/ directory.
Moreover, the which command has a parameter -a which will print all matching path names:
$ which -a docker /usr/bin/docker /bin/docker
So we have two executable files in two different directories. The shell uses the one in the /usr/bin/ directory because the directory appears first in the PATH variable, and the file has the right permissions.
Otherwise, it will go to the next executable file in the /bin/ directory:
$ echo $PATH /home/tenzin/.cargo/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/snap/bin:/sampledir/path
4. command Command
The command command is another utility that we can use to find the path of a Linux command.
This utility tells us the difference between an executable (docker) or an alias (ls):
$ command -v docker /usr/bin/docker $ command -V docker docker is hashed (/usr/bin/docker)
We need to pass the -v or -V parameter:
$ command -v ls alias ls='ls --color=auto' $ command -V ls ls is aliased to `ls --color=auto'
Otherwise, it will run the Linux command that we supply:
$ command ls Android Downloads Pictures Templates AndroidStudioProjects file123.txt 'Screenshot from 2021-06-14 16-11-31.png' Videos .
5. type Command
The type command can not only show the path of a Linux command, but it can also tell if the target is built-in, a function, an alias, or an external executable.
Let’s show the path of a Linux command:
Without the parameter, it will show the command definition:
$ type ls ls is aliased to `ls --color=auto'
If we use the -a parameter, it shows the command definition, executable type, and its path:
$ type -a ls ls is aliased to `ls --color=auto' ls is /usr/bin/ls ls is /bin/ls
We can also use type -t to display the executable type:
$ type -t which file $ type -t command builtin $ type -t type builtin $ type -t whereis file $ type -t ls alias $ type -t docker file
6. whereis Command
Finally, let’s take a look at the whereis command. This command locates the path of the binary, source, and manual page of a given command.
If we call the utility directly, it shows all the locations of the binary, source, and manual page:
$ whereis docker docker: /usr/bin/docker /etc/docker /usr/libexec/docker /usr/share/man/man1/docker.1.gz
In addition, we can use -b parameter to show just the binary:
$ whereis -b docker docker: /usr/bin/docker /etc/docker /usr/libexec/docker
Moreover, if we want to show just the source (which does not exist on this system):
If we want to show just the manual:
$ whereis -m docker docker: /usr/share/man/man1/docker.1.gz
7. Conclusion
We can use the utilities – which, command, type, and whereis to find the path of a Linux command. Some utilities show more information than others.
As we have seen in this tutorial, there are a few caveats with some utilities, but simply put, we can use these four utilities to get more information about the Linux command we want to use.