Friday, 11 May 2012

Slightly more advanced guide to Shell Scripting

Hey guys,
In this post I hope to go through a few more advanced options when writing scripts. I'm just going to cover things like methods, parameters and a few other tricks which can make your script look pretty cool.

Methods
As a Java developer by trade I use methods quite a lot, programming without them is sort of odd, for those who don't know a 'method' or 'function' in basic terms is a section of code which can be called at a later time, you can probably see why this would be useful. 

Say you have a menu system in your script where the user must choose an option for the script to continue, each option would produce a different outcome, this is a good example of when you would want to use methods.

Examples
#!/bin/bash
echo "***************EXAMPLE SCRIPT***************"
echo "Please choose and option:"
echo " 1 =  option A" 
echo " 2 =  option B "
echo " 3 =  option C "
read option
if [[ "$option" == "1" ]]
   then
     OPTIONA
   exit 0
fi
if [[ "$option" == "2" ]]
   then
     OPTIONB
   exit 0
fi
if [[ "$option" == "3" ]]
   then
     OPTIONC
   exit 0
fi
OPTIONA () {
      echo "Hello world, this is option A"
}
OPTIONB () {
     echo "Hello world, this is option B"
}
OPTIONC () {
     echo "Hello world, this is option C"
}

Ok so I'm going to dissect this and explain what each part is doing, its quite simple really.

echo "***************EXAMPLE SCRIPT***************"
echo "Please choose and option:"
echo " 1 =  option A" 
echo " 2 =  option B "
echo " 3 =  option C "
This part is the actual menu which will be shown to the user, we use the 'read option' to read the input from the user and assign it to the variable 'option', this is so we can use it later in the if statements.

if [ "$option" == "1" ]
   then
     OPTIONA
   exit 0
fi
if [ "$option" == "2" ]
   then
     OPTIONB
   exit 0
fi
if [ "$option" == "3" ]
   then
     OPTIONC
   exit 0
fi
Here we have the if statements, quite straight forward really, what's happening is we are calling the 'option' variable, if this equals '1' for example then we call the OPTIONA method.

OPTIONA () {
      echo "Hello world, this is option A"
}
As you can see option A echo's out the line  "Hello world, this is option A". After each method the code 'exit 0' is run, this is just to exit the script cleanly. 

Parameters
A good example of parameters would be if you wanted to write a script to remove all '.txt' files from a directory. In order to do this you could write a script which takes in the directory path as a parameter. This makes the script more flexible, it gives the user the choice of which directory input. The bash shell supports up to 9 parameters which are represented in the script as '$1' (if you remember awk this might make more sense) 1 being the number of the parameter. 

Example
#!/bin/bash
(cd $1 && rm *.txt)

This is a very simple example, to run this script (lets call it remove.sh) you would do the following:
./remove.sh /home/zdrenka/pictures
The script would then assign ' /home/zdrenka/pictures' to '$1' and that's what we call a parameter, there are loads of useful ways in which to use this facility. 


Since I started scripting I have picked up bits and bobs which can make your script look pretty cool, one of which is colours. Colours can make a script look that little bit more impressive. When I write a script one of the first things I do is paste this at the top:

################################################
# Define colours
################################################
txtund=$(tput sgr 0 1)    # Underline
txtbld=$(tput bold)       # Bold
txtred=$(tput setaf 1)    # Red
txtgrn=$(tput setaf 2)    # Green
txtylw=$(tput setaf 3)    # Yellow
txtblu=$(tput setaf 4)    # Blue
txtpur=$(tput setaf 5)    # Purple
txtcyn=$(tput setaf 6)    # Cyan
txtwht=$(tput setaf 7)    # White
txtrst=$(tput sgr0) # Text reset 

the '#' are obviously comments. I wrote this a while ago and now have it saved as a template, I use the colours to highlight errors, its very useful when you have a lot of text on the screen. to use these colours we just add them to the text as shown below:

echo "${txtbld}${txtred}ERROR File does not exist ${txtrst}";

The 'txtrst' variable will reset the text back to its original colour, you need this otherwise all text below your statement will be red.

Another useful command I have come across is the 'set -e' command. Put this at the top of your script and the script will automatically quit if it comes across and error, this is good practise as if you hit an error its not usually a good idea to carry on with the script. Although if you would like to have this command skip a certain part of the code you can surround that part with 'set +e' and 'set -e'. for example:
set +e
cp *.txt *.jar *.war /home/zdrenka/Java
set -e

Without these my script would stop once it hit this cp command as there may not be any '.war', '.txt' or '.jar' files in my Java directory which would technically throw up an error.

I hope this quenches your thirst for knowledge!

8 comments:

  1. Nice tips, might be worth reorganising the example so that function definitions come before the invocation, as I was a bit confused at first when I got a "command not found" error.

    ReplyDelete
  2. Well I am so excited that I have found your post because I have been searching for some information on this for almost three hours! You've helped me a lot indeed and by reading this article I have found many new and useful information about this subject!Virtual Hosted PBX

    ReplyDelete
  3. I enjoyed reading your nice blog. I see you offer priceless info. Stumbled into this blog by chance but I'm sure glad I clicked on that link. You definitely answered all the questions I've been dying to answer for some time now. Will definitely come back for more of this. roofing southlake

    ReplyDelete
  4. I also enjoy reading the comments, but notice that alot of people should stay on topic to try and add value to the original blog post.

    ReplyDelete
  5. Hello could I use some of the material found in this entry if I reference you with a link back to your site?

    ReplyDelete
    Replies
    1. Yeah no problem, which site would it be used on?

      Delete
  6. Very interesting post! I enjoyed reading your post. I will become your subscriber and visit your web site more often. Visit my web thank you so much.

    ReplyDelete