Finding scripts with $PATH

You may have noticed in the previous section that we haven't yet called hello in quite the same way we would another program; we still have to put the ./ prefix first, or specify a full path to it. It doesn't work otherwise:

bash$ ./hello
Hello, bashuser!
bash$ /home/bashuser/hello
Hello, bashuser!
bash$ hello
bash: hello: command not found

What's missing? The answer is that we need to use the special PATH variable to specify where it can find commands such asĀ hello, without needing to specify a full filesystem path to them.

Let's take a look at the value of PATH; your own value may vary:

bash$ declare -p PATH
declare -x PATH="/usr/local/bin:/usr/bin:/bin"

We notice two things:

Each of the directories specified in the value of the PATH variable are locations to be searched, in order, for any given program that the user requests be run. The first matching command found is run, and the rest are ignored. We will call these bindirs, short for logical binary directories.

Directories in PATH are only searched for a program if a builtin, alias, or function by the requested name doesn't exist; those command types always take priority. That's why you can't replace echo by making a new program called /usr/local/bin/echo.

So, in order to run hello from anywhere on the system without having to specify its full path, we need to put it in one of the directories in that variable. Which one should we pick?