What is the unix command to find out what executable file corresponds to a given command?

Solution 1:

The command to use varies from shell to shell.

Only a shell built-in will tell one correctly what the shell will do for a given command name, since only built-ins can fully know about aliases, shell functions, other built-ins, and so forth. Remember: Not all commands correspond to executable files in the first place.

  • For the Bourne Again shell, bash, the built-in is the type command:

    $ type '['
    [ is a shell builtin
    
  • For the Fish shell, fish, The type builtin works similarly to bash. To get just the path to an executable, use command -v:

    $ type cat
    cat is /bin/cat
    $ command -v cat
    /bin/cat
    
  • For the Korn Shell, ksh, the built-in is the whence command — with type initially set up as an ordinary alias for whence -v and the command built-in with the -v option equivalent to whence:

    $ whence -v ls
    ls is a tracked alias for /bin/ls
    
  • For the Z Shell, zsh, the built-in is the whence command, with the command built-in with the -v option equivalent to whence and the built-ins type, which, and where equivalent to whence with the options -v, -c, and -ca respectively.

    $ whence ls
    /bin/ls
    
  • For the T C Shell, tcsh, the built-in is the which command — not to be confused with any external command by that name:

    > which ls
    ls: aliased to ls-F
    > which \ls
    /bin/ls
    

Further reading

  • https://unix.stackexchange.com/questions/85249/

Solution 2:

You can use which for this:

aix@aix:~$ which ls
/bin/ls

It works by searching the PATH for executable files matching the names of the arguments. Note that is does not work with shell aliases:

aix@aix:~$ alias listdir=/bin/ls
aix@aix:~$ listdir /
bin    dev   initrd.img      lib32   media  proc  selinux  tmp  vmlinuz
...
aix@aix:~$ which listdir
aix@aix:~$

type, however, does work:

aix@aix:~$ type listdir
listdir is aliased to `/bin/ls'

Solution 3:

which does not (necessarily) return the executable file. It returns the first matching file name it finds in the $PATH (or multiple like named files when using which -a)... The actual executable may be multiple links away.

  • which locate
    /usr/bin/locate
    `
  • file $(which locate)
    /usr/bin/locate: symbolic link to /etc/alternatives/locate'

The command which finds the actual executable is readlink -e,
(in conjunction with which)

  • readlink -e $(which locate)
    /usr/bin/mlocate

To see all the intermediate links:

f="$(which locate)"             # find name in $PATH
printf "# %s\n" "$f"
while f="$(readlink "$f")" ;do  # follow links to executable
    printf "# %s\n" "$f"
done

# /usr/bin/locate
# /etc/alternatives/locate
# /usr/bin/mlocate