You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
Chapter 8. Writing interactive scripts<br />
In this chapter we will discuss how to interact with the users of our scripts:<br />
♦ Printing user friendly messages and explanations<br />
♦ Catching user input<br />
♦ Prompting for user input<br />
♦ Using the file descriptors to read from and write to multiple files<br />
8.1. Displaying user messages<br />
8.1.1. Interactive or not?<br />
Some scripts run without any interaction from the user at all. Advantages of non-interactive scripts include:<br />
• The script runs in a predictable way every time.<br />
• The script can run in the background.<br />
Many scripts, however, require input from the user, or give output to the user as the script is running. The<br />
advantages of interactive scripts are, among others:<br />
• More flexible scripts can be built.<br />
• Users can customize the script as it runs or make it behave in different ways.<br />
• The script can report its progress as it runs.<br />
When writing interactive scripts, never hold back on comments. A script that prints appropriate messages is<br />
much more user-friendly and can be more easily debugged. A script might do a perfect job, but you will get a<br />
whole lot of support calls if it does not inform the user about what it is doing. So include messages that tell the<br />
user to wait for output because a calculation is being done. If possible, try to give an indication of how long<br />
the user will have to wait. If the waiting should regularly take a long time when executing a certain task, you<br />
might want to consider integrating some processing indication in the output of your script.<br />
When prompting the user for input, it is also better to give too much than too little information about the kind<br />
of data to be entered. This applies to the checking of arguments and the accompanying usage message as well.<br />
<strong>Bash</strong> has the echo and printf commands to provide comments for users, and although you should be familiar<br />
with at least the use of echo by now, we will discuss some more examples in the next sections.<br />
8.1.2. Using the echo built-in command<br />
The echo built-in command outputs its arguments, separated by spaces and terminated with a newline<br />
character. The return status is always zero. echo takes a couple of options:<br />
• -e: interprets backslash-escaped characters.<br />
• -n: suppresses the trailing newline.<br />
As an example of adding comments, we will make the feed.sh and penguin.sh from Section 7.2.1.2 a<br />
Chapter 8. Writing interactive scripts 94