Java Programming Tutorials

Java programming tutorials with many code examples!

Bash define function

Problem:

Bash allows to define functions, which is very good way to reuse parts of shell scripts. This tutorial shows how to define Bash functions and apply in scripts.

Solution:

Function can be defined using the function keyword, like so:

#!/bin/bash

# $0 is a Bash variable that resolves to script's name
function print_usage {
    echo "Usage: $0 [message]"
    echo "Prints message and exits."
    # the following line ends the script
    exit 1
}

# function parameters are accessible as variables $1, $2, ...
function my_echo {
    echo "Number of params passed to the my_echo function: $#"
    echo "${1}"
}

echo "Number of params passed to the script: $#"

if [ $# -eq 0 ]; then
    # function without arguments can be called like that:
    print_usage
else
    # all parameters passed to the script are joined
    # and passed as one to the function:
    my_echo "$*"
fi

Calling the script without parameters:

$> ./echo.sh
Number of params passed to the script: 0
Usage: ./echo.sh [message]
Prints message and exits.

Calling the script with one parameter:

$> ./echo.sh Hello
Number of params passed to the script: 1
Number of params passed to the my_echo function: 1
Hello

Calling the script with more than one parameter (note the number of parameters!):

$> ./echo.sh Hello World
Number of params passed to the script: 2
Number of params passed to the my_echo function: 1
Hello World

Remember to define function before it’s use. Otherwise you will receive the following error:

$> ./echo.sh
./echo.sh: line 4: print_usage: command not found

Defining Bash functions is basic of advanced shell scripting. From now on possibilities are endless! :-)

Share with the World!