Friday, 14 January 2011

Basic shell scripting tutorial

Kitty Kat has asked me to teach her some basic shell scripting tips. She may be interested in writing her own scripts to automate functions or tasks on the Linux machine we both use. I thought that this was a good idea, but while I was giving her some pointers as what to do, I'd share it with anyone else who may be interested.

Therefore, I'll start with the universal "hello world" program. The first part is to determine if you have a shell to use, and if you can access the echo command. From you command line (assuming it is a "$"), type in the following (without the "$"):

$ which sh
$ which echo

The response from your system should look something like this:

$ which sh
/usr/bin/sh
$ which echo
/usr/bin/echo

Variations of the path are acceptable, but something like this means there is something wrong:

$ which echo
which: no echo in (/usr/local/bin:/usr/bin:/bin)

This means that either echo is not installed on your system, or that echo is not in the PATH that your command line interface is aware of. Assuming that everything is correct, open up a text editor that you are comfortable with, and (based on the information above), type in the following:

#!/usr/bin/sh

# Hello World Program
echo "Hello World!";

Save it as a file called "helloWorld.sh", and quit out of the editor. If your which commands returned different variables from the ones used in this example, adjust your helloWorld.sh script accordingly.

By default, most Linux systems do not make scripts automatically executable. To make it executable, type the following:

$ chmod u+x helloWorld.sh

To run the script, type the following:

$ ./helloWorld.sh

The output should be:

$ ./helloWorld.sh
Hello World!

In breaking down the simple script, the first line ("#!/usr/bin/sh") tells the command line that is is a shell script. Changing it would invoke different scripting engines (for example, "#!/usr/bin/perl" would mean the contents of the script should be a perl script). The next line is a comment line - and this is designated by the use of a hash symbol ("#") preceding the other text on the line. Comments are used to improve readability, but are totally optional. The third line is the line that displays the words.

I hope to expand this article into a few more that cover a few other things to do in the shell. Just look for the "Shell Scripting" tag I will use for this series of articles.

No comments:

Post a Comment