A bash script is simply put a file containing a list of commands to be executed by the bash shell (remember, there are a number of different shells available in the Unix world).

The very simplest scripts contain a set of commands that you would normally enter from the keyboard. For example:

#! /bin/bash
# script to turn the screen blue
setterm -background blue
echo Yes, your background is now Blue

Line 1: specifies which shell should be used to interpret the commands in the script (also known as a shebang).
Line 2: is a comment (has no effect when the script is executed).
Line 3: sets the background colour.
Line 4: displays a message.

To run the script:

Make the script executable: chmod 700 mySimpleScript
Try to run the script by typing the command: mySimpleScript

You will get the error message: command not found

Remember, a linux system will only only look for commands or scripts in the directories in your search path. So the system looks for the “mySimpleScript” command in the directories /usr/bin and /bin, doesn’t find it and returns the error message.

Run the script with the command:
./mySimpleScript – which means: run mySimpleScript from the current directory

If you are getting error messages when you run the script, you can trace the lines as they execute using the command: bash -v mySimpleScript

As the script executes, each line is displayed on the screen so that you know exactly what your script is doing.

Now let us expand a bit by using variables in our script.

Variables are created when you assign a value to them ( eg: COLOR=blue ). To use the variable, put a $ before the variable name. ( eg: echo $COLOR ). Modify the mySimpleScript script to use the color variable as follows:

#! /bin/bash
setterm -background $COLOR
echo It is a $COLOR day

Test it out. Next, a script can get input from the user while it is running. Use the echo command to display a prompt on the screen and the read command to get the input.

#! /bin/bash
echo -n "Pick a screen color (blue, yellow, red ): "
read -e COLOR
setterm -background $COLOR
echo It is a $COLOR day

And lastly. You can also pass parameters to the script on the command line. Bash will accept up to 9 parameters separated by spaces. The first parameter is $1, the second parameter is $2, etc. The mySimpleScript script using input parameters is shown below.

#! /bin/bash 
setterm -background $1 
echo It is a $1 day

To run the script, use the command: mySimpleScript red

In this case, $1 will be given the value “red”.

Run the script again using the command: mySimpleScript blue

This time, $1 will have the value “blue”.

And there you go. You should now have enough information in your arsenal to get started generating all your own wonderful bash scripts!

Needless to say, nifty.

(Note: Post pretty much lifted from here, mainly to save it for my personal reference. Just in case you wanted to raise a stink about it.)