From 1513611857edbdbb523856add3c7d8f45ea749a0 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 14 Nov 2024 23:47:07 -0600 Subject: [PATCH] Add Execute Several Commands With Backtick Heredoc as a Ruby TIL --- README.md | 3 +- ...-several-commands-with-backtick-heredoc.md | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 ruby/execute-several-commands-with-backtick-heredoc.md diff --git a/README.md b/README.md index 866e72f..722ec8a 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/ruby/execute-several-commands-with-backtick-heredoc.md b/ruby/execute-several-commands-with-backtick-heredoc.md new file mode 100644 index 0000000..8714333 --- /dev/null +++ b/ruby/execute-several-commands-with-backtick-heredoc.md @@ -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)