Whenever you want to execute something on the command line, you can use the following syntax:
%x(command to run)
However, I want to catch an error or at least get the response so I can parse it correctly. I tried setting:
result = %x(command to run)
and using a try-catch
begin
%x(command to run)
rescue
"didn't work"
end
to no avail. How can I capture the results instead of having them printed out?
You can put a try catch inside the catch block, or you can simply throw the exception again. Its better to have finally block with your try catch so that even if an exception occurs in the catch block, finally block code gets executed.
Handling Errors Using Do-Catch. You use a do - catch statement to handle errors by running a block of code. If an error is thrown by the code in the do clause, it's matched against the catch clauses to determine which one of them can handle the error.
do – This keyword starts the block of code that contains the method that can potentially throw an error. try – You must use this keyword in front of the method that throws. Think of it like this: “You're trying to execute the method.
So this doesn't directly answer your question (won't capture the command's output). But instead of trying begin
/rescue
, you can just check the exit code ($?
) of the command:
%x(command to run)
unless $? == 0
"ack! error occurred"
end
Edit: Just remembered this new project. I think it does exactly what you want:
https://github.com/envato/safe_shell
You might want to redirect stderr to stdout:
result = %x(command to run 2>&1)
Or if you want to separate the error messages from the actual output, you can use popen3:
require 'open3'
stdin, stdout, stderr = Open3.popen3("find /proc")
Then you can read the actual output from stdout and error messages from stderr.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With