Previous Table of Contents Next

Module 158
which (BSD)


The external which command locates given commands based on your current shell environment PATH and aliases. It displays the path of executable commands that would be executed if given as commands. Each argument to which is expanded if it is an alias, then searched for along your PATH. The aliases and path values are retrieved from your @H2 = COMMAND FORMAT

Following is the general format of the which command.

    which [ commands ]


The following argument may be passed to the which command.

commands The names of commands searched for in your PATH and aliases. Only commands that would normally be executed if given as a command are displayed. Aliases are expanded into the original command and searched for as a normal command.


If an alias contains more than a single word, a diagnostic message is displayed.


Refer to the whence and whereis commands described in modules 156 and 157. The whence command is a System V equivalent.


The which command reads the ~/.cshrc file to know about aliases.


You will find which extremely useful if you write shell scripts. One of the problems with writing a shell script is recreating an existing command name. You should always use which before you create a new command. For example, if you decide you want to create a new command to list only .c files, you might name it ls. But before you do, you need to verify that no other command exists with that name. Therefore, you type which ls and press Return. You will find that ls already exists. Thus you should select another name for your command.

Another good use is to locate which copy of a command you are executing. It is not uncommon for someone, even the system administrator, to create a new command without checking first for an existing command with the same name. Thus if you are suspicious of a command you are running because it does not perform like you expect, you can use which to find which copy you are executing.


In this activity you use the which command to find the location of the vi command. Begin at the shell prompt.

1.  Type which vi and press Return. The output resembles,
    cj> which vi

Depending on which system you are on, vi may be found in one of several possible directories.
2.  Turn to Module 157 to continue the learning sequence.

Previous Table of Contents Next