1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Execute Several Commands With Backtick Heredoc as a Ruby TIL

This commit is contained in:
jbranchaud
2024-11-14 23:47:07 -06:00
parent 74514b462d
commit 1513611857
2 changed files with 40 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1506 TILs and counting..._
_1507 TILs and counting..._
---
@@ -1211,6 +1211,7 @@ _1506 TILs and counting..._
- [Enumerate A Pairing Of Every Two Sequential Items](ruby/enumerate-a-pairing-of-every-two-sequential-items.md)
- [Evaluating One-Off Commands](ruby/evaluating-one-off-commands.md)
- [Exclude Values From An Array](ruby/exclude-values-from-an-array.md)
- [Execute Several Commands With Backtick Heredoc](ruby/execute-several-commands-with-backtick-heredoc.md)
- [Exit A Process With An Error Message](ruby/exit-a-process-with-an-error-message.md)
- [Expect A Method To Be Called And Actually Call It](ruby/expect-a-method-to-be-called-and-actually-call-it.md)
- [Extract A Column Of Data From A CSV File](ruby/extract-a-column-of-data-from-a-csv-file.md)

View File

@@ -0,0 +1,38 @@
# Execute Several Commands With Backtick Heredoc
A fun feature of Ruby is that we can execute a command in a subprocess just by
wrapping it in backticks.
For instance, we might shell out to `git` to check if a file is tracked:
```ruby
`git ls-files --error-unmatch #{file_path} 2>/dev/null`
$?.success?
```
But what if we need to execute several commands? Perhaps they depend on one
another. We want them to run in the same subprocess.
For this, we can use the backtick version of a heredoc. That is a special
version of a heredoc where the delimiter is wrapped in backticks.
```ruby
puts <<`SHELL`
# Set up trap
trap 'echo "Cleaning up temp files"; rm -f *.tmp' EXIT
# Create temporary file
echo "test data" > work.tmp
# Do some work
cat work.tmp
# Trap will clean up on exit
SHELL
```
Here we set up a `trap` for file cleanup on exit, then create a file, then do
something with the file, and that's it, the process exits (triggering the
trap).
[source](https://ruby-doc.org/3.3.6/syntax/literals_rdoc.html#label-Here+Document+Literals)