Tuesday, November 17, 2009

Bash Shell Scripting Basic Hints & Tips

A Bash shell script is simply a file containing a set of commands that will be interpreted by the Bash interpreter and executed sequentially.

Here are some tips for creating & executing scripts:

Creating your script:

  1. create a file using your favourite text editor with the extension .sh
  2. always start the file with #!/bin/sh or #!/bin/bash depending on which shell script you have installed on your system. This first line looks like a comment but it's actually call a Shebang and it provides a path to the shell script interpreter to be used to run the script.
  3. don't forget to set the file attributes to allow you to execute the script. There are various ways of doing this. For example, if you want to grant execute permission to yourself you can use: chmod u+x myscript.sh or chmod ugo+x myscript.sh if you want everybody to be able to execute your script. You can also use chmod 777 myscript.sh of course.
Executing your script:

There are two ways to execute your script:

bash$ ./myscript.sh

or

bash$ myscript

The latter only works if the script is located in a directory specified in your PATH variable. The PATH variable is located in your .bashrc file in your $HOME directory. If this file doesn't exist, create a new one and add the path setting, for example if your script is located in $HOME/bin you would add the following to your file:

PATH="$HOME/bin:$PATH"

remeber to save it!, terminate your shell and start a new one as this will force a read of your new or modified .bashrc file.

Remember to put plenty of comments in your script. Apparently, 20% to 50% of the lines in your script should be comments as a guiding rule. You can add a comment to your script by putting a # at the start of a word, for example:

#!/bin/bash
# author: A.Sealy-Bell
# -o specifies the output file
# -lstdc++ links the standard c++ library

gcc -o writetofile write_to_file.cpp -lstdc++

No comments:

Unweaving the Rainbow, by Richard Dawkins

We are going to die, and that makes us the lucky ones. Most people are never going to die because they are never going to be born. The potential people who could have been here in my place but who will in fact never see the light of day outnumber the sand grains of Sahara. Certainly those unborn ghosts include greater poets than Keats, scientists greater than Newton. We know this because the set of possible people allowed by our DNA so massively outnumbers the set of actual people. In the teeth of these stupefying odds it is you and I, in our ordinariness, that are here.
RichardDawkins.net

Books I am reading this book at the moment:

Atheist

The Out Campaign: Scarlet Letter of Atheism