24.07.2018 Views

Bash-Beginners-Guide

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The commands after && are only executed when the test proves to be true; this is a shorter way to represent<br />

an if/then/fi structure.<br />

The return code of the function is often used as exit code of the entire script. You'll see a lot of initscripts<br />

ending in something like exit $RETVAL.<br />

11.1.4. Displaying functions<br />

<strong>Bash</strong> <strong>Guide</strong> for <strong>Beginners</strong><br />

All functions known by the current shell can be displayed using the set built-in without options. Functions are<br />

retained after they are used, unless they are unset after use. The which command also displays functions:<br />

[lydia@cointreau ~] which zless<br />

zless is a function<br />

zless ()<br />

{<br />

zcat "$@" | "$PAGER"<br />

}<br />

[lydia@cointreau ~] echo $PAGER<br />

less<br />

This is the sort of function that is typically configured in the user's shell resource configuration files.<br />

Functions are more flexible than aliases and provide a simple and easy way of adapting the user environment.<br />

Here's one for DOS users:<br />

dir ()<br />

{<br />

ls -F --color=auto -lF --color=always "$@" | less -r<br />

}<br />

11.2. Examples of functions in scripts<br />

11.2.1. Recycling<br />

There are plenty of scripts on your system that use functions as a structured way of handling series of<br />

commands. On some Linux systems, for instance, you will find the /etc/rc.d/init.d/functions<br />

definition file, which is sourced in all init scripts. Using this method, common tasks such as checking if a<br />

process runs, starting or stopping a daemon and so on, only have to be written once, in a general way. If the<br />

same task is needed again, the code is recycled.<br />

You could make your own /etc/functions file that contains all functions that you use regularly on your<br />

system, in different scripts. Just put the line<br />

. /etc/functions<br />

somewhere at the start of the script and you can recycle functions.<br />

Chapter 11. Functions 133

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!