Friday, February 5, 2010

Shell Programming - 2nd Exercises

1. Accessing the Variables

a=hello
b="hello world"
maximum=20
echo $a $b $maximum

2. If statement

if date | grep Fri
then
echo Its Friday!
fi

3. Logical Testing

if date | grep Fri && test `date +'%H'` -gt 9
then
echo Its Friday, its hometime!!!
fi

4. If statement and Command Line Arguments

if test "$1" = "Friday"
then
echo "The typed argument is Friday,Welcome to PASS"
fi

5. Case statement

#!/bin/sh
echo \n Command MENU\n
echo a. Current data and time
echo b. Users currently logged in
echo c. Name of the working directory\n
echo Enter a,b, or c: \c
read answer
echo
case $answer in
a)
date
;;
b)
who
;;
c)
pwd
;;
*)
echo There is no selection: $answer
;;
esac

6. For Loop

for i in 3 7
do
echo " $i * 5 is `expr $i \* 5` "
done

7. File name printing using for loop

#!/bin/bash
for filename in *
do
echo $filename
done

8. While loop

read i
while test "$i" -gt 0
do
i=`expr $i - 1`
echo $i
done

9. While with Input string

INPUT_STRING=hello
while [ "$INPUT_STRING" != "bye" ]
do
echo "Please type something in (bye to quit)"
read INPUT_STRING
echo "You typed: $INPUT_STRING"
done

10. Function

hello()
{
k1=`expr $1 \* $2`
echo $k1
return
}
echo The example of function.
hello $1 $2

2 comments: