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

Add Get The Output Of Running A System Program as a Ruby TIL

This commit is contained in:
jbranchaud
2022-06-05 13:49:46 -05:00
parent d1bbbb8843
commit 8b2bc4748f
2 changed files with 27 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).
_1218 TILs and counting..._
_1219 TILs and counting..._
---
@@ -984,6 +984,7 @@ _1218 TILs and counting..._
- [Generate A Signed JWT Token](ruby/generate-a-signed-jwt-token.md)
- [Generate Ruby Version And Gemset Files With RVM](ruby/generate-ruby-version-and-gemset-files-with-rvm.md)
- [Get Info About Your RubyGems Environment](ruby/get-info-about-your-ruby-gems-environment.md)
- [Get The Output Of Running A System Program](ruby/get-the-output-of-running-a-system-program.md)
- [Identify Outdated Gems](ruby/identify-outdated-gems.md)
- [If You Detect None](ruby/if-you-detect-none.md)
- [Iterate With An Offset Index](ruby/iterate-with-an-offset-index.md)

View File

@@ -0,0 +1,25 @@
# Get The Output Of Running A System Program
Ruby has a [variety of ways](https://stackoverflow.com/a/18623297/535590) to
execute a system program within a Ruby process. The backticks approach is the
handy shorthand approach to reach for if you want to capture the output of the
command.
For instance, let's say I want to capture the connection string credentials
output by running a `heroku` command. When the command is wrapped in backticks,
Ruby will execute it in a subprocess and the output of the command will be the
return value.
```ruby
result = `heroku pg:credentials:url DATABASE_URL --app my-app`
# extract connection details
connection_info = result.split("\n")[2].strip
```
With the result in hand, I can use Ruby to parse out the details I'm interested
in.
Backticks does two other nice things. It allows for string interpolation and it
puts the process status (e.g. exit code) on
[`$?`](check-return-status-of-running-a-shell-command.md).