O'Reilly logo

Linux Shell Scripting Cookbook by Sarath Lakshman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Functions and arguments

Like any other scripting languages, Bash also supports functions. Let's see how to define and use functions.

How to do it...

A function can be defined as follows:

function fname()
{
statements;
}

Or alternately,

fname()
{
statements;
}

A function can be invoked just by using its name:

$ fname ; # executes function

Arguments can be passed to functions and can be accessed by our script:

fname arg1 arg2 ; # passing args

Following is the definition of the function fname. In the fname function, we have included various ways of accessing the function arguments.

fname() { echo $1, $2; #Accessing arg1 and arg2 echo "$@"; # Printing all arguments as list at once echo "$*"; # Similar to $@, but arguments taken as single entity return 0; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required