Skip to content

Commit 70f344b

Browse files
authored
Added heredocs and herestrings (#47)
* Added heredoc * Edited heredoc and added herestring
1 parent 4738a0e commit 70f344b

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

ebook/en/content/023-bash-redirection.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,49 @@ Output:
172172
18 ryan
173173
```
174174

175+
# HereDocument
176+
177+
The symbol `<<` can be used to create a temporary file [heredoc] and redirect from it at the command line.
178+
```
179+
COMMAND << EOF
180+
ContentOfDocument
181+
...
182+
...
183+
EOF
184+
```
185+
186+
Note here that `EOF` represents the delimiter (end of file) of the heredoc. In fact, we use any alphanumeric word in it's place to signify the start and end of the file. For instance, this is a valid heredoc:
187+
```
188+
cat << randomword1
189+
This script will print these lines on the terminal.
190+
Note that cat only accepts a filename as it's argument. Using this heredoc,
191+
we can create a temporary file with these lines as it's content and pass
192+
that file as the argument to cat.
193+
randomword1
194+
```
195+
196+
Effectively it will appear as if the contents of the heredoc are piped into the command. This can make the script very clean if multiple lines need to be piped into a program.
197+
198+
Further, we can attach more pipes as shown:
199+
```
200+
cat << randomword1 | wc
201+
This script will print these lines on the terminal.
202+
Note that cat only accepts a filename as it's argument. Using this heredoc,
203+
we can create a temporary file with these lines as it's content and pass
204+
that file as the argument to cat.
205+
randomword1
206+
```
207+
208+
Also, pre-defined variables can be used inside the documents.
209+
210+
# HereString
211+
212+
Herestrings are quite similar to heredocs but use `<<<`. These are used for single line strings that have to be piped into some program. This looks cleaner that heredocs as we don't have to specify the delimiter.
213+
214+
```
215+
cat <<<"this is an easy way of passing strings to the stdin of a program (here wc)" | wc
216+
```
217+
175218
## Summary
176219
|**Operator** |**Description** |
177220
|:---|:---|
@@ -180,3 +223,5 @@ Output:
180223
|`<`|`Read input from a file`|
181224
|`2>`|`Redirect error messages`|
182225
|`\|`|`Send the output from one program as input to another program`|
226+
|`<<`|`Pipe multiple lines into a program cleanly`|
227+
|`<<<`|`Pipe a single line into a program cleanly`|

0 commit comments

Comments
 (0)