Defining functions

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. ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.