Home / code / shell

Functions in Bash shell

As programs get longer and more complex, they become more difficult to design, code, and maintain. As with any large endeavor, it is often useful to break a single, large task into a number of smaller tasks.
In short you make block of commands that you can call upon later (once or several times).

This is the block of commands

function today
{
 echo "today is :"
 date +"%A, %B %-d, %Y"
}
and you call upon it, by simply mentioning the name:
today
Just make sure the you place the block of commands (body of the function),
before you call upon the function.

You don't need to start the block of commands with function, you can do it without.
But it think it makes it more clear.

today
{
 echo "today is :"
 date +"%A, %B %-d, %Y"
}
Works just as well. (At least in bash v4.0)

It is a simple as that.

Function arguments

You can pass arguments to the function the same as you pass arguments to a script.
They just don't have names ($1, $2, ...).

today argument1 "argument 2"
in the function you can call them with $1 and $2.
today
{
 echo $1
 echo $2
}

 

TOP

Latest script:

 

Books: