Accepting Input While a Script Is Running

In the previous section, we showed you that you can require that information be provided along with the script in order for the script to run, but it's easy to forget to input the information and thus not get the results you expected. You can also require input while a script is running. The script runs, you input some information, and then the script continues (probably) using the information that you input (Figure 10.8). In this case, the script counts misspelled words, but you can apply it to anything you want.

Figure 10.8. You can also input information while a script is running.

To Accept Input While a Script Is Running:


pico retentive

Use your favorite editor to edit your script.


echo -e "Which file do you want to analyze?"

Specify the text for the prompt that you'll see onscreen. Here, the onscreen text will read, "Which file do you want to analyze?"


read choice

At whatever point in the script you want the script to accept information, type read followed by the name of the variable to accept the input. Here, we name the variable choice.


echo "$choice has `cat $choice | spell | wc -l` misspelled words

Echo a phrase (and embedded command) to check the spelling, count the misspelled words, and report the number for the file specified. At each place where the filename should appear, substitute $choice.


echo -e "and was last changed \c"

Echo another line with text and (because of the \c)no line break at the end of the line.


ls -l $choice | awk '{ print "at " $8 " on " $6 " " $7 }'

This very long and complex line uses awk to pluck the time, month, and day of the month fields out of the ls -l listing for the file given as $i (Figure 10.8). See Chapter 6 for details about awk.


Save and exit.

You have the hang of this by now.



Run the script (after making it executable and specifying the current directory, if necessary) and provide a filename when prompted, as shown in Code Listing 10.7.


  • A great example of a use of prompted input is configuration files. See Using Input to Customize Your Environment in Chapter 17 for details and a specific example.

  • See Chapter 8 for more information about setting up configuration files and starting scripts upon log in.

  • You can use a set of lines like echo -e "Please enter the name: \c" and read name to have the input line and the introduction to it both appear on the same line.

Code Listing 10.7. Accepting input while a script runs helps ensure that you don't forget to type it in, and still gives customized results.

[ejr@hobbes scripting]$ ./retentive Which file do you want to analyze? testfile testfile has      11 misspelled words and was last changed at 05:08 on Jan 12 [ejr@hobbes scripting]$ 

Unix(c) Visual Quickstart Guide
UNIX, Third Edition
ISBN: 0321442458
EAN: 2147483647
Year: 2006
Pages: 251

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: