How gsh Finds a Command

gsh has a special variable, PATH, which specifies the directories and order of directories to search for shell utilities. This variable is often setup in the gshrc file although it can be changed as often as needed. The purpose of the PATH environment variable was discussed in the Section called Customizing the Shell Environment in the Chapter called Getting Started with the GNO Shell.

When gsh starts up, it searches all directories specified in the PATH environment variable and establishes a table of all commands, called a hash table. Because of this table, gsh "knows" where a command is and can execute the command much faster than searching through all directories every time the command is entered.

The search process begins with alias names. See the Section called Using Aliases. If an alias is found that matches the command, the alias is replaced with its value and the command-line is again parsed. If it was not an alias, gsh checks to see if it was a special built-in utility. The search process then searches for the name in the hash table. If an entry is found in the hash table, the path name of the command is retrieved and the command is executed. If an entry is not found, the current path is searched. If the command name is not found, an error results.

When the PATH environment variable is changed, gsh does not automatically recreate the command hash table. You need to issue the command rehash to recreate the hash table. The more pathnames specified, the greater the delay in starting gsh and in invoking the rehash command. The following shell script changes PATH and invokes the rehash command in one step.


echo Resetting PATH variable $PATH to $1
set path=$1
rehash

The $1 variable will be expanded with the first argument passed to the script.

rehash should also be used if a new utility is copied to one of the directories specified in the PATH variable. Of course, it is possible to specify the absolute pathname of any command, but this is undesirable if the command is frequently used.