It's cool if your script is capable of executing a list of commands, but it will be much better if you can make it interactive. This way, the script can ask a user for input, and the user can decide how to run the script. To make a script interactive, you can use the read command, followed by the name of a variable. This variable is used as a label to the input of the user; the cool part is that you can use it later in the script to check what exactly the user entered. Listing 27-5 shows an example of an interactive script. You'll also learn a new method to display script output on the screen.
Listing 27-5. Making Your Script Interactive #!/bin/bash
# Send a message to the world
Tell us, what message do you want to pass to the world today? Don't hesitate, anything is allowed, just tell me what friendly message you want to enter. EOF
read message echo "$message"
In the previous script, the first new item you can see is the here document, which is an alternative way to echo text to the user's screen; it is particularly useful if you want to display some lines of text on the user's screen. The advantage of using this construction is that you open it by using cat << followed by anything. In this example, I've used EOF (to refer to end of file), but if you want to use mydoggie instead, that's fine as well. Just make sure the opening statement for the here document is on a line by itself. Next, enter all the text you want to enter, and last, close the here document by referring to the text you've entered on a single line.
After the here document, the read command asks the user for some input. The input is placed in the temporary variable message, which is echoed in the last line of the script. Notice as well that to define the variable, no dollar sign is required, but to display the contents of the variable, you have to prepend a dollar sign. Otherwise, echo would have no way of knowing that you are referring to a variable. Listing 27-6 shows exactly what this script will do when you run it.
Listing 27-6. Running the Interactive Script SFO:~/bin # ./hello
Tell us, what message do you want to pass to the world today? Don't hesitate, anything is allowed, just tell me what friendly message you want to enter Good morning folks Good morning folks
Was this article helpful?