You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: ebook/en/content/023-bash-redirection.md
+45Lines changed: 45 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -172,6 +172,49 @@ Output:
172
172
18 ryan
173
173
```
174
174
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
+
175
218
## Summary
176
219
|**Operator**|**Description**|
177
220
|:---|:---|
@@ -180,3 +223,5 @@ Output:
180
223
|`<`|`Read input from a file`|
181
224
|`2>`|`Redirect error messages`|
182
225
|`\|`|`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