Bash Scripting By Example

I have never found it easy to learn something new without either a having need to do so or an opportunity for practical application.

No matter how many times I read bash scripting manuals and tutorials it was all just a bunch of hello worlds and loops that count to ten. Nothing much stuck until I had something that I wanted to do.

It was then that I began learning, remembering what I learned and appreciating how useful bash scripting could be.

There are any number of bash scripting references available. I do not intend to write another. Nor do I presume to be an expert at bash scripting. I learned what I know by working through other folk's scripts and then filling in the blanks from the man pages and the net.

In the following sections I will present scripts that I have written, explain how they work and in so doing perhaps provide the uninitiated with enough of an understanding of bash scripting to inspire them to open up an editor and get their hands dirty.

All the scripts I present in this series work. Feel free to copy them, run them on your machine and have a play at modifying them to see what happens. Any text editor will do. I use geany when working GUI and mcedit (because I'm lazy) when I am working CLI. Both of these editors support syntax highlighting which is very helpful when reading and editing scripts. If you are using KDE try using kate.

You will have to make your scripts executable. Use chmod +x [scriptname]. You can test your scripts using the command bash -n [scriptname].

I keep my scripts in /usr/local/bin but often save them into /home/~[somewhere] when writing them. If I want to run the script I'm working on and it isn't in my PATH I usually cd into the directory and run the script as ./[scriptname].

You can test a script for errors without running it with the command bash -n [scriptname].

I suggest that these articles be read in order as each article will assume that the reader understands what has been introduced in the previous article(s). I will explain only what is required to understand how a script works. For further information check the man pages, online resources, etc.


Rick Miles

24 Feb, 2012