Presented by, Mr. Satish Pise Experiment No. 12 Presented by, Mr. Satish Pise
Function Creating Functions function_name () { list of commands } Example: #!/bin/sh # Define your function here Hello () { echo "Hello World" } # Invoke your function Hello
Pass Parameters to a Function: #!/bin/sh # Define your function here Hello () { echo "Hello World $1 $2" } # Invoke your function Hello Satish Pise
Returning Values from Functions: #!/bin/sh # Define your function here Hello () { echo "Hello World $1 $2" return 10 } # Invoke your function Hello Satish Pise # Capture value returned by last command ret=$? echo "Return value is $ret"
Array Variables and Functions #!/bin/bash # array variable to function test function testit { local newarray newarray=(`echo "$@"`) echo "The new array value is: ${newarray[*]}" } myarray=(1 2 3 4 5) echo "The original array is ${myarray[*]}" testit ${myarray[*]}
Using the return command Example #!/bin/bash # using the return command in a function function dbl { read -p "Enter a value: " value echo "doubling the value" return $[ $value * 2 ] if [ $? –eq 0 ] then echo “False” else echo “True” } dbl echo "The new value is $?"
Nested Functions #!/bin/sh # Calling one function from another number_one () { echo "This is the first function speaking..." number_two } number_two () { echo "This is now the second function speaking..." } # Calling function one. number_one
Handling variables in a function Functions use two types of variables: ■ Global ■ Local #!/bin/bash # using a global variable to pass a value function dbl { value=$[ $value * 2 ] } read -p "Enter a value: " value dbl echo "The new value is: $value"
#!/bin/bash # demonstrating the local keyword function func1 { local temp=$[ $value + 5 ] result=$[ $temp * 2 ] } temp=4 value=6 func1 echo "The result is $result" if [ $temp -gt $value ] then echo "temp is larger" else echo "temp is smaller" fi