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
-
name() {
-
statements
-
}
Example
-
#!/bin/sh
-
sum() (
-
echo $(($A + $B))
-
)
-
A=2
-
B=5
-
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
-
while [ condition ]
-
do
-
# statement
-
done
Example
-
#!/bin/sh
-
count=$1 # Initialise count to first parameter
-
while [ $count -gt 0 ] # While count is greater than 5 do
-
do
-
echo “Loop $count” # Display Loop
-
count=$(expr $count -1) # Decrement count by 1
-
done
For While Loop
The For loop takes the following form:
-
For variable in word
-
do
-
# statement
-
done
Example
-
#!/bin/sh
-
for count in 1 2 3 4 5
-
do
-
echo “Loop $count” # Display Loop
-
done



