Functions

In addition to aliases, bash also offers functions. They work in much the same way as aliases, in that some function name of your choosing is assigned to a more complex construction. However, in this case that construction is a small program rather than a simple command substitution. Functions have a simple syntax:

[ function ] name () { command-list; }

This declaration defines a function called name. function is optional, and the parentheses after name are required if function is omitted. The body of the function is the command-list between the curly brackets ({ and }). This list is a series of commands, separated by semicolons or by newlines. The series of commands is executed whenever name is specified as a command. The simple lsps alias shown earlier could be implemented as a function like this:

$ lsps () { ls -l; ps; }

Using this new function as a command yields exactly the same result the alias did. However, if you implement this command as a function, parameters can be added to the command. Here is a new version of the same function, this time entered on multiple lines (which eliminates the need for semicolons within the function):

$ lsps () {
> ls -l $1
> ps aux | grep `/bin/basename $1`
> }

The > characters come from bash during interactive entry, indicating that bash is awaiting additional function commands or the } character, which terminates the function definition (this is called the secondary shell prompt). This new function allows us to enter a single argument ...

Get LPI Linux Certification in a Nutshell, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.