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.

Of course you could have opened your mail program to check the results; this is just to demonstrate that the<br />

script sends a decent mail with "To:", "Subject:" and "From:" header lines.<br />

Many more examples using case statements can be found in your system's init script directory. The startup<br />

scripts use start and stop cases to run or stop system processes. A theoretical example can be found in the<br />

next section.<br />

7.3.2. Initscript example<br />

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

Initscripts often make use of case statements for starting, stopping and querying system services. This is an<br />

excerpt of the script that starts Anacron, a daemon that runs commands periodically with a frequency<br />

specified in days.<br />

case "$1" in<br />

start)<br />

start<br />

;;<br />

stop)<br />

stop<br />

;;<br />

status)<br />

status anacron<br />

;;<br />

restart)<br />

stop<br />

start<br />

;;<br />

condrestart)<br />

if test "x`pidof anacron`" != x; then<br />

stop<br />

start<br />

fi<br />

;;<br />

*)<br />

echo $"Usage: $0 {start|stop|restart|condrestart|status}"<br />

exit 1<br />

esac<br />

The tasks to execute in each case, such as stopping and starting the daemon, are defined in functions, which<br />

are partially sourced from the /etc/rc.d/init.d/functions file. See Chapter 11 for more<br />

explanation.<br />

7.4. Summary<br />

In this chapter we learned how to build conditions into our scripts so that different actions can be undertaken<br />

upon success or failure of a command. The actions can be determined using the if statement. This allows you<br />

to perform arithmetic and string comparisons, and testing of exit code, input and files needed by the script.<br />

A simple if/then/fi test often preceeds commands in a shell script in order to prevent output generation, so that<br />

the script can easily be run in the background or through the cron facility. More complex definitions of<br />

conditions are usually put in a case statement.<br />

Chapter 7. Conditional statements 92

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

Saved successfully!

Ooh no, something went wrong!