Chapter 10. Shell Scripting Functions

In writing shell scripts, you will often find yourself repeating the same code over and over again. Repeatedly typing the same code can be tiring and can lead to errors. This is where shell scripting functions should be used. Shell functions are used to simplify your shell scripts, making them easier to read and maintain.

Shell functions are like a magic box: You throw some things into it, it begins to shake and glow with a holy aura, and then out pops your data, magically changed. The magic that is performed on your data is a set of common operations that you have encapsulated into the function and given a name. A function is simply a way of taking a group of commands and putting a name on them. The bash man page describes functions as storing "a series of commands for later execution. When the name of a shell function is used as a simple command name, the list of commands associated with that function name is executed."

Other programming languages call functions subroutines. In essence they are atomic shell scripts, having their own exit codes and arguments. The main difference is that they run within your current shell script. This means that you have one instantiation of the shell, rather than spawning a new instance of the shell for each function. Instead of defining functions, you can put your functions into separate shell scripts, in separate files, and then run those scripts from within your shell script. However, this means you have to ...

Get Beginning Shell Scripting 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.