Writing your first shell function

← Chapter 9: FunctionsHomeDisplaying functions →

We humans are certainly an intelligent species. We work with others and we depend on each other for common tasks. For example, you depend on a milkman to deliver milk in milk bottles or cartons. This logic applies to computer programs including shell scripts. When scripts gets complex you need to use divide and conquer technique.

Shell functions

  • Sometime shell scripts get complicated.
  • To avoid large and complicated scripts use functions.
  • You divide large scripts into a small chunks/entities called functions.
  • Functions makes shell script modular and easy to use.
  • Function avoids repetitive code. For example, is_root_user() function can be reused by various shell scripts to determine whether logged on user is root or not.
  • Function performs a specific task. For example, add or delete a user account.
  • Function used like normal command.
  • In other high level programming languages function is also known as procedure, method, subroutine, or routine.

Writing the hello() function

Type the following command at a shell prompt:

hello() { echo 'Hello world!' ; }

Invoking the hello() function

hello() function can be used like normal command. To execute, simply type:


Passing the arguments to the hello() function

You can pass command line arguments to user defined functions. Define hello as follows:

hello() { echo "Hello $1, let us be a friend." ; }

You can hello function and pass an argument as follows:

hello Vivek

Sample outputs:

Hello Vivek, let us be a friend.
  • One line functions inside { ... } must end with a semicolon. Otherwise you get an error on screen:
xrpm() { rpm2cpio "$1" | cpio -idmv }

Above will not work. However, the following will work (notice semicolon at the end):

xrpm() { rpm2cpio "$1" | cpio -idmv; }
← Chapter 9: FunctionsHomeDisplaying functions →