A shell script is a text file that is interpreted as a series of commands executed one after the other to achieve the desired result. It can cater for interactivity and complexity where decisions are required on certain conditions.
Here is an example of what a shell script looks like
#!/bin/bash
#
# Prog: Sample Shell Script, outputs Hello World
# Author : Jayant C Varma
#
echo "Hello World"
What does it all mean?
The first line indicates to the kernel that this is a script. So every script should start with the first line being
#!/bin/bash
, now if one was to use python or perl as the scripting language instead of bash, then the line would correspondingly change to #!/usr/bin/python
or #!/bin/perl
, The path that folows the #! is the path to where the interpreter lies, so if you have a custom language that you might want to use, you can specify the path to the interpreter and it would work.The # is a comment, and it is a good idea to document and write on the top after the first line about the author and the function of the program.
The main guts of the program that outputs the data is the line
echo "Hello World"
that prints to the terminal the words Hello World.Is that all that is required to make a script?
Yes, that is all that is required to make a script. Running the file on its own will not work as it is just a text file. So to run it we can use the command line
$ > bash myscript.sh
this shall run the script caled myscript.sh
To make the script run on its own, we need to midify the file from being an ordinary file to an executable file, we do so by changing the file permissions using the command chmod.
$ > chmod +x myscript.sh
Now the myscript.sh file is no longer an odinary text file, but an executable script file
to run the same, we can simply type, at the command line
$ > ./myscript.sh
We shall see in other posts why do we use the ./ before the filename instead of just typing the myscript.sh, an exercise for you, try it out and see what happens if you do not include the ./