How to find out where a command was run from in linux
Suppose I ran a command in unix like ls
or rm
and the path variable is set below
PATH=$JAVA_HOME/bin:.:$ORACLE_HOME/bin:/sbin:/usr/sbin:/usr/bin:/usr/ccs/bin:$COBDIR/bin:/sbin:/bin:/usr/local/bin:/bin
How can we know that the command ls
started some path? ls
(just an example) can be in /sbin
as well/usr/bin
So, I would like to know where is he from?
I cannot afford to search the entire directory and know where the entire directory lies ls
. is there a direct search method ls
it worked with?
source to share
When you run an external command in bash, bash hashes that command to avoid having to look up the path twice. The command hash
can tell you which command was run. If the command has not been run within the hash, it will result in an error.
$ hash -t ls
-bash: hash: ls: not found
$ ls foo
$ hash -t ls
/bin/ls
It is useful to know how the commands differ hash
, which
and type
.
-
hash
tells you which path / command was used / hashed. If your PATH or filesystem changes over ahash
lifetime, ithash
can tell you about the commands that happened before this change. -
which
is an external command that looks for a command in an environment variablePATH
. -
type
is a built-in command that looks for a command in a local variablePATH
that may (but hardly ever) be different from that in the environment.
For details on how this works, see help hash
bash.
source to share
In addition to other responses, which are referred to which
, type
, hash
, you can also use the the whereis (1) (if installed on your system).
whereis
tells you the standard places where the team should be.
If your interactive shell is zsh , you can also use a word =ls
like. echo =ls
or ls =ls
to see which one is ls
referring to the shell.
And you can also use an alias ls
or have a shell function ls
masquarading the executable /bin/ls
, etc. Of course, programs can run /bin/ls
without wrapping (e.g. using plain fork
+ execve
...)
Read also execvp (3) and environment (7)
source to share