8000 Added heredocs and herestrings by ek234 · Pull Request #47 · bobbyiliev/introduction-to-bash-scripting · GitHub
[go: up one dir, main page]

Skip to content

Added heredocs and herestrings #47

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 1, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions ebook/en/content/023-bash-redirection.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,49 @@ Output:
18 ryan
```

# HereDocument

The symbol `<<` can be used to create a temporary file [heredoc] and redirect from it at the command line.
```
COMMAND << EOF
ContentOfDocument
...
...
EOF
```

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:
```
cat << randomword1
This script will print these lines on the terminal.
Note that cat only accepts a filename as it's argument. Using this heredoc,
we can create a temporary file with these lines as it's content and pass
that file as the argument to cat.
randomword1
```

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.

Further, we can attach more pipes as shown:
```
cat << randomword1 | wc
This script will print these lines on the terminal.
Note that cat only accepts a filename as it's argument. Using this heredoc,
we can create a temporary file with these lines as it's content and pass
that file as the argument to cat.
randomword1
```

Also, pre-defined variables can be used inside the documents.

# HereString

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.

```
cat <<<"this is an easy way of passing strings to the stdin of a program (here wc)" | wc
```

## Summary
|**Operator** |**Description** |
|:---|:---|
Expand All @@ -180,3 +223,5 @@ Output:
|`<`|`Read input from a file`|
|`2>`|`Redirect error messages`|
|`\|`|`Send the output from one program as input to another program`|
|`<<`|`Pipe multiple lines into a program cleanly`|
|`<<<`|`Pipe a single line into a program cleanly`|
0