Summary

In this chapter, we have presented Bash functions. Functions are generic chains of commands that can be defined once, before being called multiple times. Functions are reusable and can be shared between multiple scripts.

Variable scopes were introduced. The variables we've seen thus far were always globally scoped: they were available to the entire script. However, with the introduction of functions, we encounter locally scoped variables. These are only accessible within a function and marked with the local keyword.

We learned that functions can have their own independent set of parameters, which can be passed as arguments when the function is called. We proved that these are in fact different from the global arguments passed to the script (unless all arguments are passed through to the function, of course). We gave an example about returning output from a function using stdout, which we could capture by encapsulating the function call in a command substitution.

In the second half of this chapter, we turned our attention to creating a function library: an independent script without actual commands, which can be included (via the source command) in another script. As soon as the library is sourced in another script, all functions defined in the library can then be used by the script. We spent the remainder of this chapter showing how this was done, while simultaneously expanding our function library with some practical utility functions.

We ended the chapter with an exercise for the reader, to make sure all functions defined in this chapter are included in their own personal function library.

The following commands were introduced in this chapter: top, free, declare, case, rev, and return.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.167.87