Functions and arguments

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

How to do it...

We can create functions to perform tasks and we can also create functions that take parameters (also called arguments) as you can see in the following steps:

  1. A function can be defined as follows:
    function fname()
    {
        statements;
    }
    Or alternately,
    fname()
    {
        statements;
    }
  2. A function can be invoked just by using its name:
    $ fname ; # executes function
    
  3. 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 ...

Get Linux Shell Scripting Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.