What AreBash Functions?

Alike to other coding languages, Bash allows you to create functions from within your code or script.

Finally, we call the function welcome by simply using it’s name,welcome.

Article image

Shutterstock

The resulting output may look interesting, or even confusing at first.

However, it is logical and easy to follow.

“first”, and this why the first line of output is indeedfirst.

A simple Bash function

We then callfunc2and we pass two strings"a"and"b"to the function.

The output iscbaas can be expected by scanning over the code and noting the variable names etc.

However, the code is complex and takes a little getting used to.

A more advanced Bash function with variable passing

First, we define a functionfunc3in which we create a local variable namedREVERSE.

Therevcommand prints the input received from the pipe (or otherwise) in reverse.

It is past integrally.

Example with local variables and returning values

Next, still from within thefunc3function, we print the output.

Note that there is absolutely no connection between the’global’REVERSEvariable and thelocalREVERSEvariable inside the script.

Bash function and local variable example exemplifying two of the learning points seen so far