Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby system call get information about command failure

Tags:

shell

unix

ruby

Say I have a simple command line interpreter like this:

while true
  print '> '
  cmd = gets.chomp
  break if cmd =~ /^(exit|quit)/
  system(cmd) || puts('Command not found or invalid.')
end

I would like to, instead of the "Command not found or invalid." message get an actual error message, like one you would get from bash. How would I do this?

like image 222
HRÓÐÓLFR Avatar asked Mar 30 '26 17:03

HRÓÐÓLFR


1 Answers

well, if it's unix-like system you could actually append 2>&1 to your command:

system(cmd + ' 2>&1 ')

which would redirect your stderr to stdout

another way is using %x[...] :

irb(main):027:0> def hello
irb(main):029:2*   %x[hello]
irb(main):030:2> rescue Exception => e
irb(main):031:2>   puts e.message
irb(main):033:1> end
=> nil
irb(main):034:0> hello
No such file or directory - hello
=> nil
irb(main):035:0>

meaning, you can rescue the command execution and return the exception message

like image 175
Vlad Khomich Avatar answered Apr 01 '26 08:04

Vlad Khomich