Our first script – Hello World
Since we learned basic commands to use Linux OS, we will now write our first Shell script called hello.sh
. You can use any editor of your choice such as vi, gedit, nano, and other similar editors. I prefer to use the vi editor.
- Create a new
hello.sh
file as follows: - Save the newly created file.
The #!/bin/bash
line is called the shebang line. The combination of the characters #
and !
is called the magic number. The shell uses this to call the intended shell such as /bin/bash
in this case. This should always be the first line in a Shell script.
The next few lines in the Shell script are self explanatory.
- Any line starting with
#
, will be treated as a comment line. An exception to this would be the first line with #!/bin/bash
- The
echo
command will print Hello World
on the screen - The
ls
command will display directory content on the console - The
date
command will show the current date and time
We can execute the newly created file by the following commands:
- Technique one:
- Technique two:
By running any of the preceding commands, we are adding executable permission to our newly created file. You will learn more about file permissions in later in this same chapter.
By running the preceding command, we are executing hello.sh
as the executable file. By technique one, we passed filename as an argument to Bash shell.
The output of executing hello.sh
will be as follows:
Since we have successfully executed our first script, we will proceed to develop a more advanced script, hello1.sh
. Please create the new script hello.sh
as follows:
The output of executing hello.sh
will be as follows:
You will learn about the LOGNAME
, uname
, and other similar commands as we go on with the book.