[root@rhel1 tmp]# cat function3.sh #!/bin/bash # Returning value to function multiplication () { expr $1 \* $2 } ans=$(multiplication $1 $2) echo The multiplication of $1 and $2 is: $ans [root@rhel1 tmp]#
In the above example we are passing two arguments $1 and $2 which are given while executing the shell script. Within the function we do multiplication of those arguments and sent it back to calling location. Then its initialized with variable called “ans” which is used for printing the returned value.
Let’s have look at the execution of the same.
[root@rhel1 tmp]# ./function3.sh 3 5 The multiplication of 3 and 5 is: 15
Reusing the actual commands with parameters
We can also write the function with same name of the commands. Basically we will be wrapping the actual commands by providing the options to it.
[root@rhel1 tmp]# cat function4.sh #!/bin/bash # wrapper function date () { command date +%D } date [root@rhel1 tmp]#
In the above example of wrapping the command, we have taken “date” command as the name of the function and we have wrapped it using option “+%D”.
[root@rhel1 tmp]# ./function4.sh 01/14/17
So ideally our normal date command returns “Sat Jan 14 02:14:47 BDT 2017” as output, However our wrapprd output is giving output as “01/14/17” because of wrapping.
Leave a Reply