Shell functions

From Linux Bash Shell Scripting Tutorial Wiki
Jump to navigation Jump to search

The shell functions are used to modularize shell script. You can create generic functions and put them in a text file. This text file can be re-used and all functions can be called as and when required. For example, a function file called /etc/nixcraft/functions.sh can be called from test.sh as follows:

source /etc/nixcraft/functions.sh
# call function called foo and bar
foo

# call bar()
bar

# call updateNamed
updateNamed "cyberciti.com"

You can defining functions in /etc/nixcraft/functions.sh using the following syntax: The more complicated your shell programs get, the more you will want to

functionName() {
  command1
  command2
}

OR

functionName() {
  arg1=$1
  command1 on $arg1
}

OR

functionName() {
  arg1=$1
  command1 on $arg1
  return $something
}