Functions and Aliases

Learn about similarities and differences between functions and aliases.

Similarity between functions and aliases

We declared the mem function. It prints statistics on memory usage. The following alias does the same thing:

alias mem="cat /proc/meminfo"

It looks like functions and aliases work the same way. What should we choose, then?

Functions and aliases have only one aspect in common: they are both built-in Bash mechanisms. From the user’s point of view, they both shorten long commands. However, these mechanisms work in completely different ways. Let’s explore how each works.

Aliases

An alias replaces one text with another in a typed command. In other words, Bash finds a part of the command that matches the alias name. Then, the shell replaces it with the alias value. Finally, Bash executes the resulting command.

To better understand aliases, let’s suppose we declare the alias for the cat utility. It adds the -n option to the utility call. This option adds line numbers to the cat output. The alias declaration looks like this:

alias cat="cat -n"

Whenever we type a command that starts with the word “cat”, Bash replaces it with the cat -n. For example, we can type this command:

cat ~/.bashrc

Bash inserts the alias value here, and the command becomes like this:

cat -n ~/.bashrc

Bash replaced the word cat with cat -n. It did not change the parameter, which is the ~/.bashrc path in this case.

For Windows users

We can force Bash to insert an alias without executing the resulting command. To do so, type the command and press the Ctrl+Alt+E keystroke.

Run the commands discussed in this lesson in the terminal below.

Get hands-on with 1200+ tech skills courses.