Commands are executable files, think of them like that. To use a command means you need to run an executable file so you have to provide it's path(where this executable file resides).
For example, if I want to use date
command I should type /bin/date
assuming the executable file for date
resides in /bin directory. But wait!
This is not what we do, we type date
from anywhere in terminal without typing /bin/date. So the question is how shell knows where to find the path of the command executable file without asking you to provide this path?
The answer is 'environment variables'. In Linux and other operating systems there is an environment variable called $PATH. This variable saves all paths that shell uses to search for a command executable file. Try typing
echo $PATH
You may see something like that:
rahma@rahma:~$ echo $PATH
/home/rahma/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/local/go/bin
rahma@rahma:~$
My PATH environment variable has a lot of Paths separated by colons. Shell uses paths in $PATH environment variable sequentially to search for the command executable file you entered and run it.
Let's have an example:
Let's assume you're a go developer. When you started learning go you installed it by doing something like that:
wget https://golang.org/dl/go1.17.2.linux-amd64.tar.gz
What exactly this command do?
This command downloads all dependencies and executable files to start using go, but to run go
command from anywhere in terminal you have to add the path of the directory that contains go executable file to $PATH environment variable and if you don't, you will need to provide the path of go executable file every time you want to use go
command.
Summary
$PATH environment variable contains all paths that your shell needs to search inside to run your command. That's why you don't provide any path before you run a command.