About bash functions
- Also called
Shell Functions
- Once a function is defined, it is used like a "regular" command
- Shell functions are executed in the current shell context; no new process is created to interpret them.
Function Syntax
- Functions are declared using this syntax:
1fname () compound-command [ redirections ]
2
3or
4
5function fname [()] compound-command [ redirections ]
1hello () {
2 printf "1: %s\n" $1
3 printf "2: %s\n" $2
4}
5
6function hello2 {
7 printf "This is hello2"
8}
- Create those functions by using source command
- Call your functions as if it was a "regular" command:
- If you omit the parentheses and you don't use the function keyword, bash cannot understand you are creating a new function.
So this is not good:
1hello {
2 printf "1: %s\n" $1
3 printf "2: %s\n" $2
4}
- You cannot specify parameters inside the function parentheses.
- Delete your function by using unset command
Complete funcionts example
1$ cat func1
2#!/usr/bin/bash
3#
4
5hello () {
6 printf "1: %s\n" $1
7 printf "2: %s\n" $2
8}
9
10function hello2 {
11 printf "This is hello2"
12}
13
14$ source func1
15$
16$ hello Dave Jane
171: Dave
182: Jane
19$ hello
201:
212:
22$ hello2
23This is hello2$
24$