We can define a function as a new name given to a saved compound command, which is run each time a command of that name is called. That definition is somewhat dense, so we'll break it down with some examples.
A simple function definition in one line to print our home directory might take the following form:
bash$ home() { printf '%s\n' "$HOME" ; }
This definition has a few parts:
- A function name, followed by a pair of parentheses. The name must start with a letter, and the rest of the name must be only letters, numbers, or underscores. Bash allows a space before the parentheses, if you like. In this case, our function is named home.
- An opening curly bracket, to open the compound command that forms the body of the function. This must be followed by a space.
- At least one command, each one followed by a control operator, in this case a semicolon, to run the command and pause execution until it completes. If you leave the control operator out, you'll get a syntax error. A newline counts as a control operator.
- A closing curly bracket to complete the compound command.
You might have seen the function keyword used as an alternative way to declare functions, such as function mkcd { ... }. We recommend the mkcd() { ... } syntax instead, as it's consistent between shells.
After the preceding function is defined in an interactive shell, it can be run with the home command, and Bash's type builtin reports the home name as referring to a function:
bash$ home
/home/bashuser
bash$ type home
home is a function
home ()
{
printf '%s\n' "$HOME"
}