Bash Functions
Bash Functions
Subtitle
Function:
The commands between the curly braces ({}) are called the body of the
function.
The curly braces must be separated from the body by spaces or newlines.
Defining a function doesn’t execute it. To invoke a bash function, simply use
the function name. Commands between the curly braces are executed
whenever the function is called in the shell script.
The function definition must be placed before any calls to the function.
When using single line “compacted” functions, a semicolon ; must follow the
last command in the function.
Variables Scope
When a bash function completes, its return value is the status of the last
statement executed in the function, 0 for success and non-zero decimal
number in the 1 - 255 range for failure.
The return status can be specified by using the return keyword, and it is
assigned to the variable $?.
Passing Arguments to Bash Functions
To pass any number of arguments to the bash function simply put them right
after the function’s name, separated by a space.
•The passed parameters are $1, $2, $3 … $n, corresponding to the position of the
parameter after the function’s name.
•The $0 variable is reserved for the function’s name.
•The $# variable holds the number of positional parameters/arguments passed to the
function.
•The $* and $@ variables hold all positional parameters/arguments passed to the
function.
When double-quoted, "$*" expands to a single string separated by space (the first
character of IFS) - "$1 $2 $n".
•When double-quoted, "$@" expands to separate strings - "$1" "$2" "$n".
•When not double-quoted, $* and $@ are the same.
Task :write a bash script to make function that calculate
summation of two numbers.