< Day Day Up > |
7.12. The here document and InputThe here document accepts inline text for a program expecting input, such as mail , sort , or cat , until a user -defined terminator is reached. It is often used in shell scripts for creating menus . The command receiving the input is appended with a << symbol, followed by a user-defined word or symbol, and a newline. The next lines of text will be the lines of input to be sent to the command. The input is terminated when the user-defined word or symbol is then placed on a line by itself in the leftmost column (it cannot have spaces surrounding it). The word is used in place of Ctrl-D to stop the program from reading input. Example 7.42.1 $ sort # Sort waits for user input if it does get a file pears apples bananas ^D (Ctrl-D) # User presses Ctrl-D to stop input to sort (Output) apples bananas pears $ 2 $ sort <<DONE # DONE is a user-defined terminator > pears > apples # The user input is called the "document" > bananas 3 DONE # Marks end of here document # Here is where input stops (Output) 4 apples bananas pears 5 $ EXPLANATION
If the terminator is preceded by the << “ operator, leading tabs, and only tabs, may precede the final terminator. The user-defined terminating word or symbol must match exactly from "here" to "here." The following examples illustrate the use of the here document at the command line to demonstrate the syntax. It is much more practical to use them in scripts. Example 7.43.5 Hello there ellie The time is Wed April 22 19:42:16 PST 2004 I can't wait to see you!!! 6 $ EXPLANATION
Example 7.44.1 $ cat << DONE > Hello there > What's up? > Bye now The time is `date`. 2 > DONE Hello there What's up? Bye now The time is Thu Oct 28 19:48:23 PST 2004. $ EXPLANATION
7.12.1 Now What?Now that we have completed our discussion on the interactive shell, it is time to combine many of these features in scripts, to produce programs that will automate repetitive tasks , produce information, monitor processes, and so on. If you are not a programmer, writing shell scripts may be a good place for you to start. It's fun and you get results quickly. |
< Day Day Up > |