2023-10-20 | UNIX | #Words: 315
In Linux, when we write a script, we must use an explicit path to use the script, for example: ./helloworld
. If enter helloworld
directly, we will be prompted Command 'helloworld' not found
, which is very inconvenient.
The reason is the system automatically searches all bin
directories contained in the $PATH
environment variable to find the commands used. We look at the $PATH
and see:
$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
These directories are separated by colons. For example, use nano
will searched and found /bin/nano
.
So we need to create a bin
directory under our user directory ~
and move the script into this directory (if there is a /home/username/bin
or ` ~/bin directory in your variable
$PATH`, you can use it directly without the below operation):
$ mkdir bin
$ mv helloworld bin
Add below to ~/.bashrc
file (if there is not ~/.bashrc
, create one):
export PATH=~/bin:"$PATH"
But now you will notice that using command directly still doesn’t work, beacuse bin
created is not in $PATH
. We can quit terminal and reopen or reboot, system will automatically add it to $PATH
. If not convenient to reboot, you can use below command to active:
$ source .bashrc
or
$ . .bashrc
.
is the same as the source
command. It is a built-in command of the shell to read a specified shell command and treat it as keyboard input.
I hope these will help someone in need~