Writing functions

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Defining functionsHomeCalling functions →
  • Write shell function:
name() { 
  command list;
}
  • The idea is very simple create a modular scripts.
  • Place frequently used commands or logic in a script.
  • You can call the function whenever it is required rather writing or repeating the same code again.
  • You can create a functions file.
less /etc/init.d/functions
  • All shell functions are treated as a command.
  • You must define a function at the start of a script.
  • You must load a function file at the start of a script using source (or .) command:
. /path/to/fuctions.sh

OR

source /path/to/fuctions.sh
  • You can call function like normal command:
name
name arg1 arg2

Write a function at the start of a script

A function must be created before calling. For example, the following script (ftest.sh) will fail:

#!/bin/bash
TEST="/tmp/filename"
 
# call delete_file; fail... 
delete_file
 
# write delete_file()
delete_file(){
  echo "Deleting $TEST..."
}

Sample output:

./ftest.sh: line 5: delete_file: command not found

To avoid such problems write a function at the start of a script. Also, define all variables at the start of a script:

#!/bin/bash
# define variables at the start of script 
# so that it can be accessed by our function
TEST="/tmp/filename"
 
# write delete_file() function
delete_file(){
  echo "Deleting $TEST..."
}
 
# call delete_file
delete_file
← Defining functionsHomeCalling functions →