A Beginners Guide To Linux Shell Scripts
Shell scripts make our lives as Linux users far easier as they automate many complex things that we need to do every day. Combine these with cron and you have yourself a winner. Using a combination of the two can result in some very powerful scripts such as one to automatically check for updates then do update automatically at 2 am, or one to back up the file system weekly on a Sunday.
Bash scripts are coded in a special language known as bash (Bourne Again Shell) which is the most common shell to create scripts in. People often make the mistake of thinking that a bash script and a shell script are the same thing. Actually, there are very few shell commands available, but far more bash commands, and no single user knows them all!
In this article I will assume that you meant bash scripts as they are the most common scripts in Linux land. The format of a bash script is often to open it in your favorite editor then save it as a .sh file.
To show you what a bash script does I will use the very simple “Hello World” example, which will echo “Hello World!” into the terminal. So without further ado open your favorite text editor and type in the following:
echo “Hello World!”
The first line explains to the Linux kernel that we would like to use the bash engine to run this script and, contrary to the popular belief that it is a comment, it is called the shebang line. The second line should hopefully be self-explanatory. Save it into a scripts folder (if it isn’t there, use: mkdir ~/scripts to create it in your home folder) as hello.sh so that it is easy to find later.
Now open up a new terminal window, go to your scripts directory using cd ~/scripts and finally type in: ./hello.sh if it displays “Hello World!” you have just run your first bash script!
If it tells you that the script cannot be executed due to a permissions error, run the following to rectify it which will give you execute powers on the script: chmod +x ./hello.sh (I am assuming that you are still in the scripts folder at this point.)
Let’s try something a but more complicated shall we? This time I am going to introduce you to variables which are very useful in bash because you can change the value throughout the script. Open a new file and this time type in:
HW=“Hello World Number 2”
In this script, HW holds the string and you are echoing it_,_ changing the variable and then echoing it again, simplez!
In this article I have gone through the main points that you need to get started with Bash but by no means have I covered everything. There are functions and input variables to make very complex and interesting scripts. I personally use one to inform me when my web server is no longer sending ping replies back which means it is down.
For more example scripts and a full guide on how to use bash see this page.