Working with Functions

An element that can be useful in longer shell scripts is the function. A function is a subroutine in a script that is labeled by a name. Using functions makes it easier to refer to certain command sequences that have to be used more than once in a script. You could use it, for example, to create a generic error message if something goes wrong. You have two ways of defining functions:

function functionname command1 command2 commandn

Alternatively, you can do the same thing using the following:

functionname () {

command1 command2 commandn

To increase the readability of a script, it is a good idea to use functions if you need certain code sequences more than once. Also, list all your functions at the beginning of the script to be able to easily maintain them. Listing 27-25 gives an example of a script where a function displays an error message. This script is a replacement for the file command, with the difference that this script displays a more elegant error message.

Listing 27-25. Displaying Error Codes Using Functions #!/bin/bash

# This script shows the file type

# usage: filetype $1

function noarg {

echo "You have made an error"

echo "When running this script, you need to specify the name of the file that you want to check" exit 1

fi exit 0

In the previous example, the function has the name noarg. In it, some text is specified that has to be echoed to the screen when the function is called. Since the function basically defines an error message, the function makes sure the script terminates with an exit status 1. As you can see, the function is called just once in this script, when a user forgets to enter the required argument.

Was this article helpful?

0 0

Post a comment