Unix Shell Script Creating Functions

June 15, 2007 by Mark Marucot · Leave a Comment 

Functions are named code blocks that can be referenced and executed as a unit. Functions have an option to take variable number of arguments and may return a value. If function returns a value, calling the function is usually part of an expression.

Syntax

CODE:
  1. name() {
  2. statements
  3. }

Example

CODE:
  1. #!/bin/sh
  2. sum() (
  3. echo $(($A + $B))
  4. )
  5. A=2
  6. B=5
  7. sum $A $B

Unix Shell Script Looping

June 15, 2007 by Mark Marucot · Leave a Comment 

Loops are use to perform certain task multiple times. Using loops helps minimize placing code multiple time performing similar functions. Loops in Unix scripting uses for and while loops.

Do While Loop

The Do While loop takes the following form:
Syntax

CODE:
  1. while [ condition ]
  2. do
  3. # statement
  4. done

Example

CODE:
  1. #!/bin/sh
  2. count=$1 # Initialise count to first parameter
  3. while [ $count -gt 0 ] # While count is greater than 5 do
  4. do
  5. echo “Loop $count” # Display Loop
  6. count=$(expr $count -1) # Decrement count by 1
  7. done

For While Loop

The For loop takes the following form:

CODE:
  1. For variable in word
  2. do
  3. # statement
  4. done

Example

CODE:
  1. #!/bin/sh
  2. for count in 1 2 3 4 5
  3. do
  4. echo “Loop $count” # Display Loop
  5. done