LDP/LDP/guide/docbook/Bash-Beginners-Guide/chap8.xml

630 lines
38 KiB
XML

<chapter id="chap_08">
<title>Writing interactive scripts</title>
<abstract>
<para>In this chapter we will discuss how to interact with the users of our scripts:</para>
<para>
<itemizedlist>
<listitem><para>Printing user friendly messages and explanations</para></listitem>
<listitem><para>Catching user input</para></listitem>
<listitem><para>Prompting for user input</para></listitem>
<listitem><para>Using the file descriptors to read from and write to multiple files</para></listitem>
</itemizedlist>
</para>
</abstract>
<sect1 id="sect_08_01"><title>Displaying user messages</title>
<sect2 id="sect_08_01_01"><title>Interactive or not?</title>
<para>Some scripts run without any interaction from the user at all. Advantages of non-interactive scripts include:</para>
<itemizedlist>
<listitem><para>The script runs in a predictable way every time.</para></listitem>
<listitem><para>The script can run in the background.</para></listitem>
</itemizedlist>
<para>Many scripts, however, require input from the user, or give output to the user as the script is running. The advantages of interactive scripts are, among others:</para>
<itemizedlist>
<listitem><para>More flexible scripts can be built.</para></listitem>
<listitem><para>Users can customize the script as it runs or make it behave in different ways.</para></listitem>
<listitem><para>The script can report its progress as it runs.</para></listitem>
</itemizedlist>
<para>When writing interactive scripts, never hold back on comments. A script that prints appropriate messages is much more user-friendly and can be more easily debugged. A script might do a perfect job, but you will get a whole lot of support calls if it does not inform the user about what it is doing. So include messages that tell the user to wait for output because a calculation is being done. If possible, try to give an indication of how long the user will have to wait. If the waiting should regularly take a long time when executing a certain task, you might want to consider integrating some processing indication in the output of your script.</para>
<para>When prompting the user for input, it is also better to give too much than too little information about the kind of data to be entered. This applies to the checking of arguments and the accompanying usage message as well.</para>
<para>Bash has the <command>echo</command> and <command>printf</command> commands to provide comments for users, and although you should be familiar with at least the use of <command>echo</command> by now, we will discuss some more examples in the next sections.</para>
</sect2>
<sect2 id="sect_08_01_02"><title>Using the echo built-in command</title>
<para>The <command>echo</command> built-in command outputs its arguments, separated by spaces and terminated with a newline character. The return status is always zero. <command>echo</command> takes a couple of options:</para>
<itemizedlist>
<listitem><para><option>-e</option>: interprets backslash-escaped characters.</para></listitem>
<listitem><para><option>-n</option>: suppresses the trailing newline.</para></listitem>
</itemizedlist>
<para>As an example of adding comments, we will make the <filename>feed.sh</filename> and <filename>penguin.sh</filename> from <xref linkend="sect_07_02_01_02"/> a bit better:</para>
<screen>
<prompt>michel ~/test&gt;</prompt> <command>cat <filename>penguin.sh</filename></command>
#!/bin/bash
# This script lets you present different menus to Tux. He will only be happy
# when given a fish. To make it more fun, we added a couple more animals.
if [ "$menu" == "fish" ]; then
if [ "$animal" == "penguin" ]; then
echo -e "Hmmmmmm fish... Tux happy!\n"
elif [ "$animal" == "dolphin" ]; then
echo -e "\a\a\aPweetpeettreetppeterdepweet!\a\a\a\n"
else
echo -e "*prrrrrrrt*\n"
fi
else
if [ "$animal" == "penguin" ]; then
echo -e "Tux don't like that. Tux wants fish!\n"
exit 1
elif [ "$animal" == "dolphin" ]; then
echo -e "\a\a\a\a\a\aPweepwishpeeterdepweet!\a\a\a"
exit 2
else
echo -e "Will you read this sign?! Don't feed the "$animal"s!\n"
exit 3
fi
fi
<prompt>michel ~/test&gt;</prompt> <command>cat <filename>feed.sh</filename></command>
#!/bin/bash
# This script acts upon the exit status given by penguin.sh
if [ "$#" != "2" ]; then
echo -e "Usage of the feed script:\t$0 food-on-menu animal-name\n"
exit 1
else
export menu="$1"
export animal="$2"
echo -e "Feeding $menu to $animal...\n"
feed="/nethome/anny/testdir/penguin.sh"
$feed $menu $animal
result="$?"
echo -e "Done feeding.\n"
case "$result" in
1)
echo -e "Guard: \"You'd better give'm a fish, less they get violent...\"\n"
;;
2)
echo -e "Guard: \"No wonder they flee our planet...\"\n"
;;
3)
echo -e "Guard: \"Buy the food that the Zoo provides at the entry, you ***\"\n"
echo -e "Guard: \"You want to poison them, do you?\"\n"
;;
*)
echo -e "Guard: \"Don't forget the guide!\"\n"
;;
esac
fi
echo "Leaving..."
echo -e "\a\a\aThanks for visiting the Zoo, hope to see you again soon!\n"
<prompt>michel ~/test&gt;</prompt> <command>feed.sh <parameter>apple camel</parameter></command>
Feeding apple to camel...
Will you read this sign?! Don't feed the camels!
Done feeding.
Guard: "Buy the food that the Zoo provides at the entry, you ***"
Guard: "You want to poison them, do you?"
Leaving...
Thanks for visiting the Zoo, hope to see you again soon!
<prompt>michel ~/test&gt;</prompt> <command>feed.sh <parameter>apple</parameter></command>
Usage of the feed script: ./feed.sh food-on-menu animal-name
</screen>
<para>More about escape characters can be found in <xref linkend="sect_03_03_02" />. The following table gives an overview of sequences recognized by the <command>echo</command> command:</para>
<table id="tab_08_01" frame="all"><title>Escape sequences used by the echo command</title>
<tgroup cols="2" align="left" colsep="1" rowsep="1">
<thead>
<row><entry>Sequence</entry><entry>Meaning</entry></row>
</thead>
<tbody>
<row><entry>\a</entry><entry>Alert (bell).</entry></row>
<row><entry>\b</entry><entry>Backspace.</entry></row>
<row><entry>\c</entry><entry>Suppress trailing newline.</entry></row>
<row><entry>\e</entry><entry>Escape.</entry></row>
<row><entry>\f</entry><entry>Form feed.</entry></row>
<row><entry>\n</entry><entry>Newline.</entry></row>
<row><entry>\r</entry><entry>Carriage return.</entry></row>
<row><entry>\t</entry><entry>Horizontal tab.</entry></row>
<row><entry>\v</entry><entry>Vertical tab.</entry></row>
<row><entry>\\</entry><entry>Backslash.</entry></row>
<row><entry>\0NNN</entry><entry>The eight-bit character whose value is the octal value NNN (zero to three octal digits).</entry></row>
<row><entry>\NNN</entry><entry>The eight-bit character whose value is the octal value NNN (one to three octal digits).</entry></row>
<row><entry>\xHH</entry><entry>The eight-bit character whose value is the hexadecimal value (one or two hexadecimal digits).</entry></row>
</tbody>
</tgroup>
</table>
<para>For more information about the <command>printf</command> command and the way it allows you to format output, see the Bash info pages. Keep in mind that there might be differences between different versions of Bash.</para>
</sect2>
</sect1>
<sect1 id="sect_08_02"><title>Catching user input</title>
<sect2 id="sect_08_02_01"><title>Using the read built-in command</title>
<para>The <command>read</command> built-in command is the counterpart of the <command>echo</command> and <command>printf</command> commands. The syntax of the <command>read</command> command is as follows:</para>
<cmdsynopsis><command>read <option>[options]</option> <varname>NAME1 NAME2 ... NAMEN</varname></command></cmdsynopsis>
<para>One line is read from the standard input, or from the file descriptor supplied as an argument to the <option>-u</option> option. The first word of the line is assigned to the first name, <varname>NAME1</varname>, the second word to the second name, and so on, with leftover words and their intervening separators assigned to the last name, <varname>NAMEN</varname>. If there are fewer words read from the input stream than there are names, the remaining names are assigned empty values.</para>
<para>The characters in the value of the <varname>IFS</varname> variable are used to split the input line into words or tokens; see <xref linkend="sect_03_04_07" />. The backslash character may be used to remove any special meaning for the next character read and for line continuation.</para>
<para>If no names are supplied, the line read is assigned to the variable <varname>REPLY</varname>.</para>
<para>The return code of the <command>read</command> command is zero, unless an end-of-file character is encountered, if <command>read</command> times out or if an invalid file descriptor is supplied as the argument to the <option>-u</option> option.</para>
<para>The following options are supported by the Bash <command>read</command> built-in:</para>
<table id="tab_08_02" frame="all"><title>Options to the read built-in</title>
<tgroup cols="2" align="left" colsep="1" rowsep="1">
<thead>
<row><entry>Option</entry><entry>Meaning</entry></row>
</thead>
<tbody>
<row><entry>-a <varname>ANAME</varname></entry><entry>The words are assigned to sequential indexes of the array variable <varname>ANAME</varname>, starting at 0. All elements are removed from <varname>ANAME</varname> before the assignment. Other <varname>NAME</varname> arguments are ignored.</entry></row>
<row><entry>-d <varname>DELIM</varname></entry><entry>The first character of <varname>DELIM</varname> is used to terminate the input line, rather than newline.</entry></row>
<row><entry>-e</entry><entry><command>readline</command> is used to obtain the line.</entry></row>
<row><entry>-n <varname>NCHARS</varname></entry><entry><command>read</command> returns after reading <varname>NCHARS</varname> characters rather than waiting for a complete line of input.</entry></row>
<row><entry>-p <varname>PROMPT</varname></entry><entry>Display <varname>PROMPT</varname>, without a trailing newline, before attempting to read any input. The prompt is displayed only if input is coming from a terminal.</entry></row>
<row><entry>-r</entry><entry>If this option is given, backslash does not act as an escape character. The backslash is considered to be part of the line. In particular, a backslash-newline pair may not be used as a line continuation.</entry></row>
<row><entry>-s</entry><entry>Silent mode. If input is coming from a terminal, characters are not echoed.</entry></row>
<row><entry>-t <varname>TIMEOUT</varname></entry><entry>Cause <command>read</command> to time out and return failure if a complete line of input is not read within <varname>TIMEOUT</varname> seconds. This option has no effect if <command>read</command> is not reading input from the terminal or from a pipe.</entry></row>
<row><entry>-u <varname>FD</varname></entry><entry>Read input from file descriptor <varname>FD</varname>.</entry></row>
</tbody>
</tgroup>
</table>
<para>This is a straightforward example, improving on the <filename>leaptest.sh</filename> script from the previous chapter:</para>
<screen>
<prompt>michel ~/test&gt;</prompt> <command>cat <filename>leaptest.sh</filename></command>
#!/bin/bash
# This script will test if you have given a leap year or not.
echo "Type the year that you want to check (4 digits), followed by [ENTER]:"
read year
if (( ("$year" % 400) == "0" )) || (( ("$year" % 4 == "0") &amp;&amp; ("$year" % 100 !=
"0") )); then
echo "$year is a leap year."
else
echo "This is not a leap year."
fi
<prompt>michel ~/test&gt;</prompt> <command>leaptest.sh</command>
Type the year that you want to check (4 digits), followed by [ENTER]:
2000
2000 is a leap year.
</screen>
</sect2>
<sect2 id="sect_08_02_02"><title>Prompting for user input</title>
<para>The following example shows how you can use prompts to explain what the user should enter.</para>
<screen>
<prompt>michel ~/test&gt;</prompt> <command>cat <filename>books.sh</filename></command>
#!/bin/bash
# This is a program that creates a favorite book library.
books="books.txt"
echo "Hello, "$USER". This script will add your favorite book to the database."
echo -n "Enter the title and press [ENTER]: "
read title
echo -n "Enter the name of the author and press [ENTER]: "
read author
echo
grep -i "$title" "$books"
if [ $? == 0 ]; then
echo "You have already suggested a book, quitting."
exit 1
elif [ "$author" == "shakespeare" ]; then
echo "What's in a name? That which we call a rose by any other name would smell as sweet."
exit 1
else
echo -n "Enter the cost and press [ENTER]: "
read cost
if [ $cost -lt 25 ]; then
echo "$title | $author | $cost" &gt;&gt; "$books"
echo "Your book is added to the database. Thank you so much!"
else
echo "Let me look for $title by $author at the library."
exit 1
fi
fi
<prompt>michel ~/test&gt;</prompt> <command>cp <filename>books.sh /var/tmp</filename>; cd <filename>/var/tmp</filename></command>
<prompt>michel ~/test&gt;</prompt> <command>touch <filename>books</filename>; chmod <option>a+w</option> <filename>books</filename></command>
<prompt>michel ~/test&gt;</prompt> <command>books.sh</command>
Hello, michel. This script will add your favorite book to the database.
Enter the title and press [ENTER]: 1984
Enter the name of the author and press [ENTER]: Orwell
Enter the cost and press [ENTER]: 30
Let me look for 1984 by Orwell at the library.
<prompt>michel ~/test&gt;</prompt> <command>cat <filename>books</filename></command>
</screen>
<para>Note that no output is omitted here. The script only stores information about the books that Michel is interested in. It will always thank you for your suggestion, unless you already provided it.</para>
<para>Other people can now start executing the script:</para>
<screen>
<prompt>[anny@octarine tmp]$</prompt> <command>books.sh</command>
Hello, anny. This script will add your favorite book to the database.
Enter the title and press [ENTER]: Sense and Sensibility
Enter the name of the author and press [ENTER]: Austen
Enter the cost and press [ENTER]: 10
Your book is added to the database. Thank you so much!
</screen>
<para>After a while, the <filename>books</filename> list begins to look like this:</para>
<screen>
Sense and Sensibility | Austen | 10
Harry Potter and the Sorcerer's Stone | Rowling | 20
The Lord of the Rings | Tolkien | 22
To Kill a Mockingbird | Lee | 12
--output omitted--
</screen>
<para>Of course, this situation is not ideal, since everybody can edit (but not delete) Michel's files. You can solve this problem using special access modes on the script file, see <ulink url="http://www.tldp.org/LDP/intro-linux/html/sect_04_01.html#sect_04_01_06">SUID and SGID</ulink> in the Introduction to Linux guide.</para>
</sect2>
<sect2 id="sect_08_02_03"><title>Redirection and file descriptors</title>
<sect3 id="sect_08_02_03_01"><title>General</title>
<para>As you know from basic shell usage, input and output of a command may be redirected before it is executed, using a special notation - the redirection operators - interpreted by the shell. Redirection may also be used to open and close files for the current shell execution environment.</para>
<para>Redirection can also occur in a script, so that it can receive input from a file, for instance, or send output to a file. Later, the user can review the output file, or it may be used by another script as input.</para>
<para>File input and output are accomplished by integer handles that track all open files for a given process. These numeric values are known as file descriptors. The best known file descriptors are <emphasis>stdin</emphasis>, <emphasis>stdout</emphasis> and <emphasis>stderr</emphasis>, with file descriptor numbers 0, 1 and 2, respectively. These numbers and respective devices are reserved. Bash can take TCP or UDP ports on networked hosts as file descriptors as well.</para>
<para>The output below shows how the reserved file descriptors point to actual devices:</para>
<screen>
<prompt>michel ~&gt;</prompt> <command>ls <option>-l</option> <filename>/dev/std*</filename></command>
lrwxrwxrwx 1 root root 17 Oct 2 07:46 /dev/stderr -> ../proc/self/fd/2
lrwxrwxrwx 1 root root 17 Oct 2 07:46 /dev/stdin -> ../proc/self/fd/0
lrwxrwxrwx 1 root root 17 Oct 2 07:46 /dev/stdout -> ../proc/self/fd/1
<prompt>michel ~&gt;</prompt> <command>ls <option>-l</option> <filename>/proc/self/fd/[0-2]</filename></command>
lrwx------ 1 michel michel 64 Jan 23 12:11 /proc/self/fd/0 -> /dev/pts/6
lrwx------ 1 michel michel 64 Jan 23 12:11 /proc/self/fd/1 -> /dev/pts/6
lrwx------ 1 michel michel 64 Jan 23 12:11 /proc/self/fd/2 -> /dev/pts/6
</screen>
<para>Note that each process has its own view of the files under <filename>/proc/self</filename>, as it is actually a symbolic link to <filename>/proc/&lt;process_ID&gt;</filename>.</para>
<para>You might want to check <command>info MAKEDEV</command> and <command>info proc</command> for more information about <filename>/proc</filename> subdirectories and the way your system handles standard file descriptors for each running process.</para>
<para>When excuting a given command, the following steps are excuted, in order:</para>
<itemizedlist>
<listitem><para>If the standard output of a previous command is being piped to the standard input of the current command, then <filename>/proc/&lt;current_process_ID&gt;/fd/0</filename> is updated to target the same anonymous pipe as <filename>/proc/&lt;previous_process_ID/fd/1</filename>.</para></listitem>
<listitem><para>If the standard output of the current command is being piped to the standard input of the next command, then <filename>/proc/&lt;current_process_ID&gt;/fd/1</filename> is updated to target another anonymous pipe.</para></listitem>
<listitem><para>Redirection for the current command is processed from left to right.</para></listitem>
<listitem><para>Redirection <quote>N&gt;&amp;M</quote> or <quote>N&lt;&amp;M</quote> after a command has the effect of creating or updating the symbolic link <filename>/proc/self/fd/N</filename> with the same target as the symbolic link <filename>/proc/self/fd/M</filename>.</para></listitem>
<listitem><para>The redirections <quote>N&gt; file</quote> and <quote>N&lt; file</quote> have the effect of creating or updating the symbolic link <filename>/proc/self/fd/N</filename> with the target file.</para></listitem>
<listitem><para>File descriptor closure <quote>N&gt;&amp;-</quote> has the effect of deleting the symbolic link <filename>/proc/self/fd/N</filename>.</para></listitem>
<listitem><para>Only now is the current command executed.</para></listitem>
</itemizedlist>
<para>When you run a script from the command line, nothing much changes because the child shell process will use the same file descriptors as the parent. When no such parent is available, for instance when you run a script using the <emphasis>cron</emphasis> facility, the standard file descriptors are pipes or other (temporary) files, unless some form of redirection is used. This is demonstrated in the example below, which shows output from a simple <command>at</command> script:</para>
<screen>
<prompt>michel ~&gt;</prompt> <command>date</command>
Fri Jan 24 11:05:50 CET 2003
<prompt>michel ~&gt;</prompt> <command>at <parameter>1107</parameter></command>
warning: commands will be executed using (in order)
a) $SHELL b) login shell c)/bin/sh
<prompt>at&gt;</prompt> <command>ls <option>-l</option> <filename>/proc/self/fd/</filename> &gt; <filename>/var/tmp/fdtest.at</filename></command>
<prompt>at&gt;</prompt> <command>&lt;EOT&gt;</command>
job 10 at 2003-01-24 11:07
<prompt>michel ~&gt;</prompt> <command>cat <filename>/var/tmp/fdtest.at</filename></command>
total 0
lr-x------ 1 michel michel 64 Jan 24 11:07 0 -> /var/spool/at/!0000c010959eb (deleted)
l-wx------ 1 michel michel 64 Jan 24 11:07 1 -> /var/tmp/fdtest.at
l-wx------ 1 michel michel 64 Jan 24 11:07 2 -> /var/spool/at/spool/a0000c010959eb
lr-x------ 1 michel michel 64 Jan 24 11:07 3 -> /proc/21949/fd
</screen>
<para>And one with <command>cron</command>:</para>
<screen>
<prompt>michel ~&gt;</prompt> <command>crontab <option>-l</option></command>
# DO NOT EDIT THIS FILE - edit the master and reinstall.
# (/tmp/crontab.21968 installed on Fri Jan 24 11:30:41 2003)
# (Cron version -- $Id$)
32 11 * * * ls -l /proc/self/fd/ > /var/tmp/fdtest.cron
<prompt>michel ~&gt;</prompt> <command>cat <filename>/var/tmp/fdtest.cron</filename></command>
total 0
lr-x------ 1 michel michel 64 Jan 24 11:32 0 -> pipe:[124440]
l-wx------ 1 michel michel 64 Jan 24 11:32 1 -> /var/tmp/fdtest.cron
l-wx------ 1 michel michel 64 Jan 24 11:32 2 -> pipe:[124441]
lr-x------ 1 michel michel 64 Jan 24 11:32 3 -> /proc/21974/fd
</screen>
</sect3>
<sect3 id="sect_08_02_03_02"><title>Redirection of errors</title>
<para>From the previous examples, it is clear that you can provide input and output files for a script (see <xref linkend="sect_08_02_04" /> for more), but some tend to forget about redirecting errors - output which might be depended upon later on. Also, if you are lucky, errors will be mailed to you and eventual causes of failure might get revealed. If you are not as lucky, errors will cause your script to fail and won't be caught or sent anywhere, so that you can't start to do any worthwhile debugging.</para>
<para>When redirecting errors, note that the order of precedence is significant. For example, this command, issued in <filename>/var/spool</filename></para>
<screen>
<command>ls <option>-l</option> <filename>*</filename> <parameter>2</parameter>&gt; <filename>/var/tmp/unaccessible-in-spool</filename></command>
</screen>
<para>will redirect standard output of the <command>ls</command> command to the file <filename>unaccessible-in-spool</filename> in <filename>/var/tmp</filename>. The command</para>
<screen>
<command>ls <option>-l</option> <filename>*</filename> &gt; <filename>/var/tmp/spoollist</filename> <parameter>2</parameter>&gt;&amp;<parameter>1</parameter></command>
</screen>
<para>will direct both standard input and standard error to the file <filename>spoollist</filename>. The command</para>
<screen>
<command>ls <option>-l</option> <filename>*</filename> <parameter>2</parameter> &gt;&amp; <parameter>1</parameter> &gt; <filename>/var/tmp/spoollist</filename></command>
</screen>
<para>directs only the standard output to the destination file, because the standard error is copied to standard output before the standard output is redirected.</para>
<para>For convenience, errors are often redirected to <filename>/dev/null</filename>, if it is sure they will not be needed. Hundreds of examples can be found in the startup scripts for your system.</para>
<para>Bash allows for both standard output and standard error to be redirected to the file whose name is the result of the expansion of <filename>FILE</filename> with this construct:</para>
<cmdsynopsis><command>&amp;&gt; <filename>FILE</filename></command></cmdsynopsis>
<para>This is the equivalent of <command>&gt; <filename>FILE</filename> 2&gt;&amp;1</command>, the construct used in the previous set of examples. It is also often combined with redirection to <filename>/dev/null</filename>, for instance when you just want a command to execute, no matter what output or errors it gives.</para>
</sect3>
</sect2>
<sect2 id="sect_08_02_04"><title>File input and output</title>
<sect3 id="sect_08_02_04_01"><title>Using /dev/fd</title>
<para>The <filename>/dev/fd</filename> directory contains entries named <filename>0</filename>, <filename>1</filename>, <filename>2</filename>, and so on. Opening the file <filename>/dev/fd/N</filename> is equivalent to duplicating file descriptor <emphasis>N</emphasis>. If your system provides <filename>/dev/stdin</filename>, <filename>/dev/stdout</filename> and <filename>/dev/stderr</filename>, you will see that these are equivalent to <filename>/dev/fd/0</filename>, <filename>/dev/fd/1</filename> and <filename>/dev/fd/2</filename>, respectively.</para>
<para>The main use of the <filename>/dev/fd</filename> files is from the shell. This mechanism allows for programs that use pathname arguments to handle standard input and standard output in the same way as other pathnames. If <filename>/dev/fd</filename> is not available on a system, you'll have to find a way to bypass the problem. This can be done for instance using a hyphen (<emphasis>-</emphasis>) to indicate that a program should read from a pipe. An example:</para>
<screen>
<prompt>michel ~&gt;</prompt> <command>filter <filename>body.txt.gz</filename> | cat <filename>header.txt</filename> - <filename>footer.txt</filename></command>
This text is printed at the beginning of each print job and thanks the sysadmin
for setting us up such a great printing infrastructure.
Text to be filtered.
This text is printed at the end of each print job.
</screen>
<para>The <command>cat</command> command first reads the file <filename>header.txt</filename>, next its standard input which is the output of the <command>filter</command> command, and last the <filename>footer.txt</filename> file. The special meaning of the hyphen as a command-line argument to refer to the standard input or standard output is a misconception that has crept into many programs. There might also be problems when specifying hyphen as the first argument, since it might be interpreted as an option to the preceding command. Using <filename>/dev/fd</filename> allows for uniformity and prevents confusion:</para>
<screen>
<prompt>michel ~&gt;</prompt> <command>filter <filename>body.txt</filename> | cat <filename>header.txt /dev/fd/0 footer.txt</filename> | lp</command>
</screen>
<para>In this clean example, all output is additionally piped through <command>lp</command> to send it to the default printer.</para>
</sect3>
<sect3 id="sect_08_02_04_02"><title>Read and exec</title>
<sect4 id="sect_08_02_04_02_01"><title>Assigning file descriptors to files</title>
<para>Another way of looking at file descriptors is thinking of them as a way to assign a numeric value to a file. Instead of using the file name, you can use the file descriptor number. The <command>exec</command> built-in command can be used to replace the shell of the current process or to alter the file descriptors of the current shell. For example, it can be used to assign a file descriptor to a file. Use</para>
<cmdsynopsis><command>exec fdN&gt; <filename>file</filename></command></cmdsynopsis>
<para>for assigning file descriptor N to <filename>file</filename> for output, and</para>
<cmdsynopsis><command>exec fdN&lt; <filename>file</filename></command></cmdsynopsis>
<para>for assigning file descriptor N to <filename>file</filename> for input. After a file descriptor has been assigned to a file, it can be used with the shell redirection operators, as is demonstrated in the following example:</para>
<screen>
<prompt>michel ~&gt;</prompt> <command>exec <filename>4</filename>&gt; <filename>result.txt</filename></command>
<prompt>michel ~&gt;</prompt> <command>filter <filename>body.txt</filename> | cat <filename>header.txt /dev/fd/0 footer.txt</filename> &gt;&amp; <filename>4</filename></command>
<prompt>michel ~&gt;</prompt> <command>cat <filename>result.txt</filename></command>
This text is printed at the beginning of each print job and thanks the sysadmin
for setting us up such a great printing infrastructure.
Text to be filtered.
This text is printed at the end of each print job.
</screen>
<note><title>File descriptor 5</title>
<para>Using this file descriptor might cause problems, see <ulink url="http://www.tldp.org/LDP/abs/html/io-redirection.html">the Advanced Bash-Scripting Guide</ulink>, chapter 16. You are strongly advised not to use it.</para>
</note>
</sect4>
<sect4 id="sect_08_02_04_02_02"><title>Read in scripts</title>
<para>The following is an example that shows how you can alternate between file input and command line input:</para>
<screen>
<prompt>michel ~/testdir&gt;</prompt> <command>cat <filename>sysnotes.sh</filename></command>
#!/bin/bash
# This script makes an index of important config files, puts them together in
# a backup file and allows for adding comment for each file.
CONFIG=/var/tmp/sysconfig.out
rm "$CONFIG" 2&gt;/dev/null
echo "Output will be saved in $CONFIG."
# create fd 7 with same target as fd 0 (save stdin "value")
exec 7&lt;&amp;0
# update fd 0 to target file /etc/passwd
exec &lt; /etc/passwd
# Read the first line of /etc/passwd
read rootpasswd
echo "Saving root account info..."
echo "Your root account info:" &gt;&gt; "$CONFIG"
echo $rootpasswd &gt;&gt; "$CONFIG"
# update fd 0 to target fd 7 target (old fd 0 target); delete fd 7
exec 0&lt;&amp;7 7&lt;&amp;-
echo -n "Enter comment or [ENTER] for no comment: "
read comment; echo $comment &gt;&gt; "$CONFIG"
echo "Saving hosts information..."
# first prepare a hosts file not containing any comments
TEMP="/var/tmp/hosts.tmp"
cat /etc/hosts | grep -v "^#" &gt; "$TEMP"
exec 7&lt;&amp;0
exec &lt; "$TEMP"
read ip1 name1 alias1
read ip2 name2 alias2
echo "Your local host configuration:" &gt;&gt; "$CONFIG"
echo "$ip1 $name1 $alias1" &gt;&gt; "$CONFIG"
echo "$ip2 $name2 $alias2" &gt;&gt; "$CONFIG"
exec 0&lt;&amp;7 7&lt;&amp;-
echo -n "Enter comment or [ENTER] for no comment: "
read comment; echo $comment &gt;&gt; "$CONFIG"
rm "$TEMP"
<prompt>michel ~/testdir&gt;</prompt> <command>sysnotes.sh</command>
Output will be saved in /var/tmp/sysconfig.out.
Saving root account info...
Enter comment or [ENTER] for no comment: hint for password: blue lagoon
Saving hosts information...
Enter comment or [ENTER] for no comment: in central DNS
<prompt>michel ~/testdir&gt;</prompt> <command>cat <filename>/var/tmp/sysconfig.out</filename></command>
Your root account info:
root:x:0:0:root:/root:/bin/bash
hint for password: blue lagoon
Your local host configuration:
127.0.0.1 localhost.localdomain localhost
192.168.42.1 tintagel.kingarthur.com tintagel
in central DNS
</screen>
</sect4>
</sect3>
<sect3 id="sect_08_02_04_03"><title>Closing file descriptors</title>
<para>Since child processes inherit open file descriptors, it is good practice to close a file descriptor when it is no longer needed. This is done using the</para>
<cmdsynopsis><command>exec fd&lt;&amp;-</command></cmdsynopsis>
<para>syntax. In the above example, file descriptor 7, which has been assigned to standard input, is closed each time the user needs to have access to the actual standard input device, usually the keyboard.</para>
<para>The following is a simple example redirecting only standard error to a pipe:</para>
<screen>
<prompt>michel ~&gt;</prompt> <command>cat <filename>listdirs.sh</filename></command>
#!/bin/bash
# This script prints standard output unchanged, while standard error is
# redirected for processing by awk.
INPUTDIR="$1"
# fd 6 targets fd 1 target (console out) in current shell
exec 6&gt;&amp;1
# fd 1 targets pipe, fd 2 targets fd 1 target (pipe),
# fd 1 targets fd 6 target (console out), fd 6 closed, execute ls
ls "$INPUTDIR"/* 2&gt;&amp;1 &gt;&amp;6 6&gt;&amp;- \
# Closes fd 6 for awk, but not for ls.
| awk 'BEGIN { FS=":" } { print "YOU HAVE NO ACCESS TO" $2 }' 6&gt;&amp;-
# fd 6 closed for current shell
exec 6&gt;&amp;-
</screen>
</sect3>
<sect3 id="sect_08_02_04_04"><title><emphasis>Here</emphasis> documents</title>
<para>Frequently, your script might call on another program or script that requires input. The <emphasis>here</emphasis> document provides a way of instructing the shell to read input from the current source until a line containing only the search string is found (no trailing blanks). All of the lines read up to that point are then used as the standard input for a command.</para>
<para>The result is that you don't need to call on separate files; you can use shell-special characters, and it looks nicer than a bunch of <command>echo</command>'s:</para>
<screen>
<prompt>michel ~&gt;</prompt> <command>cat <filename>startsurf.sh</filename></command>
#!/bin/bash
# This script provides an easy way for users to choose between browsers.
echo "These are the web browsers on this system:"
# Start here document
cat &lt;&lt; BROWSERS
mozilla
links
lynx
konqueror
opera
netscape
BROWSERS
# End here document
echo -n "Which is your favorite? "
read browser
echo "Starting $browser, please wait..."
$browser &amp;
<prompt>michel ~&gt;</prompt> <command>startsurf.sh</command>
These are the web browsers on this system:
mozilla
links
lynx
konqueror
opera
netscape
<prompt>Which is your favorite?</prompt> <command>opera</command>
Starting opera, please wait...
</screen>
<para>Although we talk about a <emphasis>here document</emphasis>, it is supposed to be a construct within the same script. This is an example that installs a package automatically, eventhough you should normally confirm:</para>
<screen>
#!/bin/bash
# This script installs packages automatically, using yum.
if [ $# -lt 1 ]; then
echo "Usage: $0 package."
exit 1
fi
yum install $1 &lt;&lt; CONFIRM
y
CONFIRM
</screen>
<para>And this is how the script runs. When prompted with the <quote>Is this ok [y/N]</quote> string, the script answers <quote>y</quote> automatically:</para>
<screen>
<prompt>[root@picon bin]#</prompt> <command>./install.sh <parameter>tuxracer</parameter></command>
Gathering header information file(s) from server(s)
Server: Fedora Linux 2 - i386 - core
Server: Fedora Linux 2 - i386 - freshrpms
Server: JPackage 1.5 for Fedora Core 2
Server: JPackage 1.5, generic
Server: Fedora Linux 2 - i386 - updates
Finding updated packages
Downloading needed headers
Resolving dependencies
Dependencies resolved
I will do the following:
[install: tuxracer 0.61-26.i386]
<prompt>Is this ok [y/N]:</prompt> <command><keycap>Enter</keycap></command>Downloading Packages
Running test transaction:
Test transaction complete, Success!
tuxracer 100 % done 1/1
Installed: tuxracer 0.61-26.i386
Transaction(s) Complete
</screen>
</sect3>
</sect2>
</sect1>
<sect1 id="sect_08_03"><title>Summary</title>
<para>In this chapter, we learned how to provide user comments and how to prompt for user input. This is usually done using the <command>echo</command>/<command>read</command> combination. We also discussed how files can be used as input and output using file descriptors and redirection, and how this can be combined with getting input from the user.</para>
<para>We stressed the importance of providing ample message for the users of our scripts. As always when others use your scripts, it is better to give too much information than not enough. <emphasis>Here</emphasis> documents is a type of shell construct that allows creation of lists, holding choices for the users. This construct can also be used to execute otherwise interactive tasks in the background, without intervention.</para>
</sect1>
<sect1 id="sect_08_04"><title>Exercises</title>
<para>These exercises are practical applications of the constructs discussed in this chapter. When writing the scripts, you may test by using a test directory that does not contain too much data. Write each step, then test that portion of code, rather than writing everything at once.</para>
<orderedlist>
<listitem><para>Write a script that asks for the user's age. If it is equal to or higher than 16, print a message saying that this user is allowed to drink alcohol. If the user's age is below 16, print a message telling the user how many years he or she has to wait before legally being allowed to drink.</para>
<para>As an extra, calculate how much beer an 18+ user has drunk statistically (100 liters/year) and print this information for the user.</para>
</listitem>
<listitem><para>Write a script that takes one file as an argument. Use a <emphasis>here</emphasis> document that presents the user with a couple of choices for compressing the file. Possible choices could be <command>gzip</command>, <command>bzip2</command>, <command>compress</command> and <command>zip</command>. </para></listitem>
<listitem><para>Write a script called <filename>homebackup</filename> that automates <command>tar</command> so the person executing the script always uses the desired options (<option>cvp</option>) and backup destination directory (<filename>/var/backups</filename>) to make a backup of his or her home directory. Implement the following features:</para>
<itemizedlist>
<listitem><para>Test for the number of arguments. The script should run without arguments. If any arguments are present, exit after printing a usage message.</para></listitem>
<listitem><para>Determine whether the <filename>backups</filename> directory has enough free space to hold the backup.</para></listitem>
<listitem><para>Ask the user whether a full or an incremental backup is wanted. If the user does not have a full backup file yet, print a message that a full backup will be taken. In case of an incremental backup, only do this if the full backup is not older than a week.</para></listitem>
<listitem><para>Compress the backup using any compression tool. Inform the user that the script is doing this, because it might take some time, during which the user might start worrying if no output appears on the screen.</para></listitem>
<listitem><para>Print a message informing the user about the size of the compressed backup.</para></listitem>
</itemizedlist>
<para>See <command>info tar</command> or <ulink url="http://tille.garrels.be/training/tldp/c4540.html#sect_09_01_01">Introduction to Linux</ulink>, chapter 9: <quote>Preparing your data</quote> for background information.</para>
</listitem>
<listitem><para>Write a script called <filename>simple-useradd.sh</filename> that adds a local user to the system. This script should:</para>
<itemizedlist>
<listitem><para>Take only one argument, or else exit after printing a usage message.</para></listitem>
<listitem><para>Check <filename>/etc/passwd</filename> and decide on the first free user ID. Print a message containing this ID.</para></listitem>
<listitem><para>Create a private group for this user, checking the <filename>/etc/group</filename> file. Print a message containing the group ID.</para></listitem>
<listitem><para>Gather information from the operator user: a comment describing this user, choice from a list of shells (test for acceptability, else exit printing a message), expiration date for this account, extra groups of which the new user should be a member.</para></listitem>
<listitem><para>With the obtained information, add a line to <filename>/etc/passwd</filename>, <filename>/etc/group</filename> and <filename>/etc/shadow</filename>; create the user's home directory (with correct permissions!); add the user to the desired secondary groups.</para></listitem>
<listitem><para>Set the password for this user to a default known string.</para></listitem>
</itemizedlist>
</listitem>
<listitem><para>Rewrite the script from <xref linkend="sect_07_02_01_04" /> so that it reads input from the user instead of taking it from the first argument.</para></listitem>
</orderedlist>
</sect1>
</chapter>