Defining functions

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Removing functionsHomeWriting functions →

To define a function, use the following syntax:

name() compound_command ## POSIX compliant
## see the bash man page for def. of a compound command

OR

function name { ## ksh style works in bash
 command1
 command2 
}

OR

function name() { ## bash-only hybrid
 command1
 command2 
}

One Line Functions Syntax

One line functions inside { ... } must end with a semicolon:

function name { command1; command2; commandN;}

OR

name() { command1; command2; commandN;}

where name is the name of the function, and "command1; command2;" is a list of commands used in the function. You need to replace name with actual function name such as delete_account:

rollback(){
  ...
}
 
add_user(){
  ...
}
 
delete_user(){
  ...
}

Example

Define a function called mount_nas and umount_nas:

# function to mount NAS device
mount_nas(){
        # define variables
 	NASMNT=/nas10
 	NASSERVER="nas10.nixcraft.net.in"
 	NASUSER="vivek"
 	NASPASSWORD="myNasAccountPassword"
        [ ! -d $NASMNT ] && /bin/mkdir -p $NASMNT
        mount | grep -q $NASMNT
        [ $? -eq 0 ] || /bin/mount -t cifs //$NASSERVER/$NASUSER -o username=$NASUSER,password=$NASPASSWORD $NASMNT
}
 
# function to unmount NAS device
umount_nas(){
	NASMNT=/nas10
        mount | grep -q $NASMNT
        [ $? -eq 0 ] && /bin/umount $NASMNT
}

You can type your function at the beginning of the shell script:

#!/bin/bash
# define variables
NASMNT=/nas10
....
..
....
# define functions
function umount_nas(){
  /bin/mount | grep -q $NASMNT
  [ $? -eq 0 ] && /bin/umount $NASMNT
}
 
# another function
functiom mount_nas(){
  command1
  command2
}
 
....
...
### main logic ##
 
[ $? -eq 0 ] && { echo "Usage: $0 device"; exit 1; }
...
.....
 
# When you wish to access function, you use the following format:
umount_nas
← Removing functionsHomeWriting functions →