Skip to content

Commit 1513611

Browse files
committed
Add Execute Several Commands With Backtick Heredoc as a Ruby TIL
1 parent 74514b4 commit 1513611

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1506 TILs and counting..._
13+
_1507 TILs and counting..._
1414

1515
---
1616

@@ -1211,6 +1211,7 @@ _1506 TILs and counting..._
12111211
- [Enumerate A Pairing Of Every Two Sequential Items](ruby/enumerate-a-pairing-of-every-two-sequential-items.md)
12121212
- [Evaluating One-Off Commands](ruby/evaluating-one-off-commands.md)
12131213
- [Exclude Values From An Array](ruby/exclude-values-from-an-array.md)
1214+
- [Execute Several Commands With Backtick Heredoc](ruby/execute-several-commands-with-backtick-heredoc.md)
12141215
- [Exit A Process With An Error Message](ruby/exit-a-process-with-an-error-message.md)
12151216
- [Expect A Method To Be Called And Actually Call It](ruby/expect-a-method-to-be-called-and-actually-call-it.md)
12161217
- [Extract A Column Of Data From A CSV File](ruby/extract-a-column-of-data-from-a-csv-file.md)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Execute Several Commands With Backtick Heredoc
2+
3+
A fun feature of Ruby is that we can execute a command in a subprocess just by
4+
wrapping it in backticks.
5+
6+
For instance, we might shell out to `git` to check if a file is tracked:
7+
8+
```ruby
9+
`git ls-files --error-unmatch #{file_path} 2>/dev/null`
10+
$?.success?
11+
```
12+
13+
But what if we need to execute several commands? Perhaps they depend on one
14+
another. We want them to run in the same subprocess.
15+
16+
For this, we can use the backtick version of a heredoc. That is a special
17+
version of a heredoc where the delimiter is wrapped in backticks.
18+
19+
```ruby
20+
puts <<`SHELL`
21+
# Set up trap
22+
trap 'echo "Cleaning up temp files"; rm -f *.tmp' EXIT
23+
24+
# Create temporary file
25+
echo "test data" > work.tmp
26+
27+
# Do some work
28+
cat work.tmp
29+
30+
# Trap will clean up on exit
31+
SHELL
32+
```
33+
34+
Here we set up a `trap` for file cleanup on exit, then create a file, then do
35+
something with the file, and that's it, the process exits (triggering the
36+
trap).
37+
38+
[source](https://ruby-doc.org/3.3.6/syntax/literals_rdoc.html#label-Here+Document+Literals)

0 commit comments

Comments
 (0)