Using heredocs for script input

Since heredocs allow us to simply pass newline-delimited input to a command, we can use this to run an interactive script in a non-interactive manner! We have used this in practice, for instance, on database installer scripts that could only be run interactively. However, once you know the order of the questions and the input you want to supply, you can use the heredoc to supply this input to that interactive script.

Even better, we have already created a script that uses interactive input, /home/reader/scripts/chapter_11/while-interactive.shwhich we can use to show this functionality: 

reader@ubuntu:/tmp$ head /home/reader/scripts/chapter_11/while-interactive.sh
#!/bin/bash

#####################################
# Author: Sebastiaan Tammer
# Version: v1.1.0
# Date: 2018-10-28
# Description: A simple riddle in a while loop.
# Usage: ./while-interactive.sh
#####################################

reader@ubuntu:/tmp$ bash /home/reader/scripts/chapter_11/while-interactive.sh << EOF
a mouse #Try 1.
the sun #Try 2.
keyboard #Try 3.
EOF

Incorrect, please try again. #Try 1.
Incorrect, please try again. #Try 2.
Correct, congratulations! #Try 3.
Now we can continue after the while loop is done, awesome!

We know that the script continues until it gets the right answer, which is either keyboard or Keyboard. We use the heredoc to send three answers, in order, to the script: a mouse, the sun, and finally keyboard. We can correspond the output to the input quite easily.

For more verbosity, run the script with heredoc input with a bash -x, which will show you definitively that there are three tries to the riddle.

You might want to use a here document within a nested function (which will be explained in the next chapter) or within a loop. In both cases, you should already be using indentation to improve readability. However, this impacts your heredoc, because the whitespace is considered part of the input. If you find yourself in that situation, heredocs have an extra option: <<- instead of <<. When supplying the extra -, all tab characters are ignored. This allows you to indent the heredoc construction with tabs, which maintains both readability and function.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.185.169