| bash example | |
|---|---|
| 1 | # 8.1 Functions sample |
| 2 | |
| 3 | #!/bin/bash |
| 4 | function quit { |
| 5 | exit |
| 6 | } |
| 7 | function hello { |
| 8 | echo Hello! |
| 9 | } |
| 10 | hello |
| 11 | quit |
| 12 | echo foo |
| 13 | |
| 14 | Lines 2-4 contain the 'quit' function. Lines 5-7 contain the 'hello' function If you are not absolutely sure about what this script does, please try it!. |
| 15 | |
| 16 | Notice that a functions don't need to be declared in any specific order. |
| 17 | |
| 18 | When running the script you'll notice that first: the function 'hello' is called, second the 'quit' function, and the program never reaches line 10. |
| 19 | |
| 20 | 8.2 Functions with parameters sample |
| 21 | |
| 22 | #!/bin/bash |
| 23 | function quit { |
| 24 | exit |
| 25 | } |
| 26 | function e { |
| 27 | echo $1 |
| 28 | } |
| 29 | e Hello |
| 30 | e World |
| 31 | quit |
| 32 | echo foo |
| 33 | |
| 34 | |
| 35 | This script is almost identically to the previous one. The main difference is the funcion 'e'. This function, prints the first argument it receives. Arguments, within funtions, are treated in the same manner as arguments given to the script. |