Cancel

Functions in Bash

The function is essentially a set of commands that can be called numerous times. The purpose of a function is to help you to make your bash scripts more readable and to avoid writing the same code repeatedly.

Simple function, same as many programming languages. Remember function keyword is optional in bash.

1
2
3
4
5
6
function my_func() {
  echo "hello world" # any command can be here.
}

# call a function without parentheses.
my_func

Global vs Local variable

  • Global variables can be accessed from anywhere in the script regardless of the scope.
  • Local variables must be declared within the function body with the local keyword.
1
2
3
4
5
6
7
8
9
10
11
name="Yafiz Abraham" # global variable

my_func() {
  local my_message="this will only work within the function" # local variable
  echo $my_message # message will be printed inside the function.
  echo $name # will work inside the function.
}

my_func # call a function, which will work as usual.
echo "global var: " $name # will work outside the function.
echo "local var (this will not work): " $my_message # will never work outside the function.

Remember: Global variable will work anywhere in the script whereas local variable will work only inside the function.

Arguments with function

The function supports positional parameters or arguments as well to reuse function with different params or args.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
my_func() {
  echo "Hello, $1 $2"
}

# $0 is my_func
# $1 is Yafiz
# $2 is Abraham
# so on...
my_func Yafiz Abraham

# unlimited params or args can be accepted via 4 loop.
# $@ means all params or args.
function my_func() {
  for name in $@; do
    echo "Hi, $name"
  done
}

# $0 is my_func
# $1 is Yafiz
# $2 is Abraham
# $3 is 20
# $4 is Yahoo
# so on...
my_func Yafiz Abraham 20 Yahoo Google