Learning is experience, experience is learning

eric's notebook

type vs which

leave a comment »

Both the commands, type and which, can locate a command, what’s the difference?

sunny@master:~$ type -p ping
/bin/ping
sunny@master:~$ which ping
/bin/ping

By the type command:
sunny@master:~$ type type
type is a shell builtin
sunny@master:~$ type which
which is hashed (/usr/bin/which)

As the man says (man bash):

type [-aftpP] name [name …]
With no options, indicate how each name would be interpreted if
used as a command name. If the -t option is used, type prints a
string which is one of alias, keyword, function, builtin, or
file if name is an alias, shell reserved word, function,
builtin, or disk file, respectively. If the name is not found,
then nothing is printed, and an exit status of false is
returned. If the -p option is used, type either returns the
name of the disk file that would be executed if name were speci‐
fied as a command name, or nothing if “type -t name” would not
return file. The -P option forces a PATH search for each name,
even if “type -t name” would not return file. If a command is
hashed, -p and -P print the hashed value, not necessarily the
file that appears first in PATH. If the -a option is used, type
prints all of the places that contain an executable named name.
This includes aliases and functions, if and only if the -p
option is not also used. The table of hashed commands is not
consulted when using -a. The -f option suppresses shell func‐
tion lookup, as with the command builtin. type returns true if
all of the arguments are found, false if any are not found.

man which:

which returns the pathnames of the files (or links) which would be exe‐
cuted in the current environment, had its arguments been given as com‐
mands 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.

So you’ll know, which can locate a command but does not know whether you run in shell is the found command or not, and type can do this by contrast.

Written by ericliang

12/05/2010 at 18:50

Posted in Enjoy linux

Leave a comment