UNIX LAB EXPERIMENT NO :7 Usage of user defined functions Administration

Functions

A function may return a value in one of four different ways:
  • Change the state of a variable or variables
  • Use the exit command to end the shell script
  • Use the return command to end the function, and return the supplied value to the calling section of the shell script
  • echo output to stdout, which will be caught by the caller just as c=`expr $a + $b` is caught
Example1:

myfunc()
{
  echo "I was called as : $@"
  x=2
}
### Main script starts here 
echo "Script was called with $@"
x=1
echo "x is $x"
myfunc 1 2 3
echo "x is $x"

Example-2:
#!/bin/sh

factorial()
{
  if [ "$1" -gt "1" ]; then
    i=`expr $1 - 1`
    j=`factorial $i`
    k=`expr $1 \* $j`
    echo $k
  else
    echo 1
  fi
}
while :
do
  echo "Enter a number:"
  read x
  factorial $x
done    

No comments

Algorithms and Programs

  Algorithms and Programs Both the algorithms and programs are used to solve problems, but they are not the same things in terms of their fu...