Table of Contents
Now is the last step in 3 steps how to write a bash script file. This article will learn about the script file location and script execution. The execution of the script sounds very simple, but sometimes, you don’t understand why it doesn’t work as expected.
Script file location
Normally, when you write and assign the executable permissions to the script file, it is done. You can execute it with the following command (eg I use hello_world script file).
danie@linuxmint ~ $ ./hello_worldBut if you do not provide the path of the script file, you will get the following error:
danie@linuxmint ~ $ hello_world
bash: hello_world: command not foundIn fact, if you encounter the above situation, it’s not a problem for your script. It is simply that the system cannot know where your script is.
The system’s default PATH
By default, the Linux system contains executable libraries in the /bin (binaries) directory. So, when you execute the script without providing the path of the file. The system will automatically find in its default directory /bin and as a result it cannot find your script.
/bin is not the only directory in the system that contains executable files, there are other directories and may be declared by you.
The list of executable directories is in an environment variable of the system called PATH. To display the entire list of those directories, use the following command:
danie@linuxmint ~ $ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
Now, you can put the script file into one of the above directories, if you want to put it in your directory such as /home/danie/writebash.com. You can do the following steps in turn.
danie@linuxmint ~ $ mkdir /home/danie/writebash.com
danie@linuxmint ~ $ mv hello_world /home/danie/writebash.com/
danie@linuxmint ~ $ export PATH=~/writebash.com:"$PATH"Now let’s see if the PATH variable already contains your directory.
danie@linuxmint ~ $ echo $PATH
/home/danie/writebash.com:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/gamesExecute script file
Now, the /home/danie/writebash.com folder is already in the list of system folders that will automatically search for executable files. Your script has also been placed in that directory, meaning that you can execute the script without calling the file path.
Simply calling the script name is like calling other common commands in the system.
danie@linuxmint ~ $ hello_world
Hello WorldSo you have all the basic steps to write and execute a bash script file. Practice a lot so you can feel comfortable using the script.
(This is an article from my old blog that has been inactive for a long time, I don’t want to throw it away so I will keep it and hope it helps someone).