Shell Functions  «Prev  Next»
Lesson 1

Writing Shell functions

In the previous module, you learned about common problems with shell scripts. Shell scripts are often difficult to debug when they are long. In this module, we will discuss separating your script into logical units called functions. Because functions perform just part of the work of a script, they make a long script easier to write, maintain, and debug. In this module, you will learn to:
  1. Define the purpose of a function in a shell script
  2. Create a correctly formed shell script function
  3. Invoke a function within a script
  4. Write a script that uses multiple functions
  5. Use variables to share data with a function
  6. Write a reusable function
  7. Determine how and when to use functions that you did not write

Unix Shell Programming

Define the purpose of a function in a Unix Shell Script?

In a Unix Shell Script, you can define the purpose of a function by adding a comment at the beginning of the function definition that describes what the function does. This comment is often referred to as the function's "documentation string."
The syntax for defining a function in a Unix Shell Script is as follows:
function_name() {
  # Documentation string
  commands
}

To add a documentation string, simply add a comment after the opening brace that describes what the function does. For example:
say_hello() {
  # This function prints a greeting message to the screen
  echo "Hello, world!"
}

In this example, the documentation string explains that the say_hello function prints a greeting message to the screen. Adding a documentation string to your functions can be helpful when you or others read your code later, as it provides a quick reference for what the function does without having to read through the entire function's implementation.