Here strings

The last thing we'd like to discuss in this chapter is the here string. It is very similar to the here document (hence the name), but it deals with a single string, instead of a document (who would have thought!).

This construct, which uses the <<< syntax, can be used to supply text input to a command that perhaps normally only accepts input from stdin or a file. A good example for this is bc, which is a simple calculator (part of the GNU Project).

Normally, you use it in one of two ways: sending input to stdin via a pipe, or by pointing bc to a file:

reader@ubuntu:/tmp$ echo "2^8" | bc
256

reader@ubuntu:/tmp$ echo "4*4" > math
reader@ubuntu:/tmp$ bc math
bc 1.07.1
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
16
^C
(interrupt) use quit to exit.
quit

When used with stdin, bc returns the result of the calculation. When used with a file, bc opens an interactive session, which we need to manually close by entering quit. Both ways seem a little too much work for what we want to achieve.

Let's look at how a here string fixes this:

reader@ubuntu:/tmp$ bc <<< 2^8
256

There we go. Just a simple here string as input (which is sent to stdin of the command), and we get the same functionality as an echo with a pipe. However, now it is just a single command, instead of a chain. Simple but effective, just the way we like it!

..................Content has been hidden....................

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