Using functions in bash is fairly useful to organise and reuse code. Here is quick beginner tutorial with examples on using bash functions.
Declaring functions in bash
Functions can be declared either using function f1 () or f1 () as shown below:
#!/bin/bash
function f1 () {
echo "in f1"
}
f2 () {
echo "in f2"
}
f1
f2in f1 in f2
Env: GNU bash, version 4.2.46
Passing arguments to functions in bash
Arguments are accessible using $@ or $1, $2, etc.
#!/bin/bash
function f1 () {
echo "in f1 all args=$@"
echo "in f1 first arg=$1"
}
f1 A B Bin f1 all args=A B B in f1 first arg=A
Env: GNU bash, version 4.2.46
Calling functions in bash
Function f1 can directly called as f1 in as sub-shell command (e.g. $(f1)). When called with sub-shell mode it will return the outcome of echo, etc. instead of printing.
#!/bin/bash
function f1 () {
echo "in f1"
}
## inline function mode
f1
# in sub-shell mode
ret=$(f1)
echo "ret=$ret"in f1 ret=in f1
Env: GNU bash, version 4.2.46