functions

Supervisor

Administrator
Apr 27, 2015
1,865
2,538
295
The big advantage using functions is using them multiple times, but only writing the code once :)
Remember that functions always have to precede "normal" code.
There are two different ways you can use functions in bash:
  1. function function_name {
    command...
    }
  2. function_name (){
    command...
    }
I always use the second one, but this is up to you. Another thing which come in handy is to call scripts with parameters, so functin_name foo will call the function with the parameter $1=foo. Example:
Code:
#!/bin/bash
foo="1"
foobar (){
printf "variable foo is \"$foo\""
if [ -n "$1" ]
then printf " and you called this function with \$1=\"$1\".\n"
else printf " and you did not call this function with a variable. Why didn't you do that? It would have been funny :(\n"
fi
}
printf "Type \"foobar variable\":   "
read -r answer
$answer
exit
88d11bdb9f.png
 
Top