Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching command-line errors using %x

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?

like image 664
sethvargo Avatar asked Jan 23 '11 02:01

sethvargo


People also ask

How do you handle errors in catch block?

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.

Do catch with error Swift?

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 catch vs try catch Swift?

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.


2 Answers

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

like image 90
cam Avatar answered Oct 14 '22 09:10

cam


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.

like image 23
Tonttu Avatar answered Oct 14 '22 11:10

Tonttu