Unix Shell Scripting

Links external: index | commands
and internal: preamble | script 1 | script 2 | script 3 | script 4 | commands | end

Preamble

Search the web and you can find thousands of reference - putting something like 'unix shell script reference sh' into say Yahoo! and searching will yield upwards of 300,000 hits! That was in 2006. Now (2008-09-07) it is more than a million hits. Maybe Yahoo! has improved its search algorithms ;=))

Do not be fooled by the age of many of these references - many are as valid today as the day they were first written ;=))

top | commands


Script 1

There are a number of different 'shells' to use, but perhaps the most common is the Standard Borne Shell, sh ... here is a very simple 'Hello World' script -

#!/bin/sh
echo "Hello World\n"

The first line is the 'shell' to run, and 'echo' is a built-in command that outputs to the console. The quotation marks around the text makes it one block, and the '\n', read as 'escape n', adds an additional line feed to the output - the echo already adds one ...

I use 'gedit', part of the gnome desktop for editing script files. Save the above into a file, say test1.sh, and use 'chmod' to make it executable ... this step is important!

$ chmod 755 test1.sh

Then to run the script -

$ ./test1.sh

This obviously should give an output of -

Hello World
  

Note the 'extra' line in the output. Our first script is done ;=))

top | commands


Scrip 2 - Parameters

When a script is run, any 'parameters' entered after the script name can also be access using a '$' character ...

Here is a reference, circa 1996 - http://www.injunea.demon.co.uk/pages/page204.htm - with some simple tutorials ... a simple understanding can come from this simple example, given on that site.

This script shows how to access the script name, '$0', and the parameters as entered, '$1', '$2', etc, and some other 'specials', using this '$' ... in general the '$' sign means for the shell to substitute the value contained in the variable following. These are some global 'variables' ...

#!/bin/sh -vx
#######################################################
# example_1.1 (c) R.H.Reepe 1996 March 28 Version 1.0 #
#######################################################
echo "Script name is [$0]"
echo "First Parameter is [$1]"
echo "Second Parameter is [$2]"
echo "This Process ID is [$$]"
echo "This Parameter Count is [$#]"
echo "All Parameters [$@]"
echo "The FLAGS are [$-]"

What editor to use to create this file, named say 'test2.sh', can also be more complicated than it should be ... To first try this example, I was using cygwin, and used a simple editor called 'nano', but now I have Ubuntu, as a dual boot, and tend to use the GUI editor 'gedit', which has colour encoding ... It was as simple as entering :-

$ nano test2.sh<enter>    (in cygwin) or
$ gedit test2.sh &<enter> (in Ubuntu)

I used the clipboard to copy the above text into the Nano editor. Nano has help along the bottom line - ctrl+o writes the data to a file, and ctrl+x exits the editor ... the GUI gedit uses the 'standard' Ctrl+S to save a file. However, I had some problem initially running this shell script ... nano, nor gedit, do not normally set up files with the 'execute' permission ... so when I tried -

$ ./test2.sh p1 p2

I got a stern warning - permission denied ... a brief tutorial on permissions can be found here - http://www.dartmouth.edu/~rc/help/faq/permissions.html - I had the use 'chmod' to set the permissions as follows -

$ chmod -c -v 0755 test2.sh

Then the command -

$ ls test2.sh -l

showed the following -

-rwxr-xr-x 1 GeoffMcLane None 397 Apr 23 19:15 test2.sh (in cygwin) or
-rwxr-xr-x 1 geoff geoff      291 2008-09-07 18:46 test2.sh (in Ubuntu)

The 'x' in the initial part of the listing denotes 'executable' ... now my command -
$ ./test2.sh p1 p2
produced the following output -

Script name is [./test1.sh]
First Parameter is [p1]
Second Parameter is [p2]
This Process ID is [168]
This Parameter Count is [2]
All Parameters [p1 p2]
The FLAGS are [hB]

Note: The '-vx' options on the first line of the script (a) echoes the command, then (b) shows it expanded, and then finally (c) executes it - removing this '-vx' and the output listing will be as above -

Simple huh?

top | commands


Script 3

Now to move on to some more advanced features ...

Of course, you must 'know' some simple unix commands that can be used, and another page of that same site - http://www.injunea.demon.co.uk/pages/page205.htm - there is a simple example of some syntax that can be used to construct a for <something> do ... done loop -

alphabet="a b c d e"                # 1 Initialise a string
count=0                             # 2 Initialise a counter
for letter in $alphabet             # 3 Set up a loop control
do                                  # 4 Begin the loop
 count=`expr $count + 1`            # 5 Increment the counter
 echo "Letter $count is [$letter]"  # 6 Display the result
done                                # 7 End of loop

Using the nano or gedit editor to add this to a test3.sh file, setting the execute permissions using chmod, then running it I get the output -

$ ./test3.sh
Letter 1 is [a]
Letter 2 is [b]
Letter 3 is [c]
Letter 4 is [d]
Letter 5 is [e]

These seven(7) lines of script shows a lot of things about shell processing ;=))
Line 1 & 2: Initializing some variables - 'alphabet', with a string of space separated values, and 'count', with a number;
Line 3 & 4: Opens up a 'for <something> do' statement, in this case for each letter in the variable $alphabet, and 'do' the following lines, until line 7 - done;
Line 5: Uses an 'expr', a simple arithmetic processor, inside '`' command shell characters - note this is NOT a simple single quotation mark, to put the sum of the current count, $count, plus 1, into count;
Line 6: Outputs the string, substituting $count for its current value, and $letter for its value, and shows that the 'for' use a space, ' ', as a delimiter when processing the 'for';
Line 7: 'done' closes the for do ... statement.

top | commands


Script 4

Similar to the above, except using a while [ something ] do ... done structure ...

alphabet="a b c d e"                                   # 1 Initialise a string
count=0                                                # 2 Initialise a counter
while [ $count -lt 5 ]                                 # 3 Set up a loop control
do                                                     # 4 Begin the loop
 count=`expr $count + 1`                               # 5 Increment the counter
 position=`expr $count + $count - 1`                   # 6 Position of next letter
 letter=`echo "$alphabet" | cut -c$position-$position` # 7 Get next letter 
 echo "Letter $count is [$letter] at $position"        # 8 Display the result
done                                                   # 9 End of loop

Again, these 9 lines of script demonstrate lots of things available to a shell script writer. Perhaps the most interesting is line 7, where the contents of $alphabet is piped, '|', to 'cut' which gets a letter at a specific position in the string ...

top | commands


Script 5

This brings us to the if [ something ] then ... [[ elif [ something ] then ... ] else ... ] fi structure, and introduces some file testing capability ....

top | commands


Commands

Some of the simple 'commands' that can be used. More details about these can often be seen by using '--help' parameter ... or 'man command', which will load the manual, if available, into a 'vi' type editor - try ':q' to exit! ...

top | commands


This site - http://www.cs.mcgill.ca/~navindra/editors/ - did have some basic information about the various editors available in unix, but is now invalid ... Often the most puzzling thing is how to 'exit' the editor, and to understand this, you need to have an idea about 'modes' ... some unix editors basically have two modes - a command mode where you can move around the document with command keys, and 'entry' mode, where what you type is added to the document ... this can take some time to grasp ...

I can say my 'understanding' of linux/unix has grown massively over the intervening 2 plus years, especially since I now have a 'real' linux, Ubuntu, running as a dual boot ;=)) and use scripts for just about ever repeated task ...

update: 13 Oct 2008, 7 Sep 2008 - started 23 Apr 2006

index -|- top -|- commands

checked by tidy  Valid HTML 4.01 Transitional