File tree 2 files changed +40
-1
lines changed
2 files changed +40
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
10
10
11
11
For a steady stream of TILs, [ sign up for my newsletter] ( https://crafty-builder-6996.ck.page/e169c61186 ) .
12
12
13
- _ 1506 TILs and counting..._
13
+ _ 1507 TILs and counting..._
14
14
15
15
---
16
16
@@ -1211,6 +1211,7 @@ _1506 TILs and counting..._
1211
1211
- [ Enumerate A Pairing Of Every Two Sequential Items] ( ruby/enumerate-a-pairing-of-every-two-sequential-items.md )
1212
1212
- [ Evaluating One-Off Commands] ( ruby/evaluating-one-off-commands.md )
1213
1213
- [ 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 )
1214
1215
- [ Exit A Process With An Error Message] ( ruby/exit-a-process-with-an-error-message.md )
1215
1216
- [ Expect A Method To Be Called And Actually Call It] ( ruby/expect-a-method-to-be-called-and-actually-call-it.md )
1216
1217
- [ Extract A Column Of Data From A CSV File] ( ruby/extract-a-column-of-data-from-a-csv-file.md )
Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments