ruby system command check exit code

后端 未结 5 545
太阳男子
太阳男子 2020-12-02 12:39

I have a bunch of system calls in ruby such as the following and I want to check their exit codes simultaneously so that my script exits out if that command fails.



        
相关标签:
5条回答
  • 2020-12-02 13:13

    From the documentation:

    system returns true if the command gives zero exit status, false for non zero exit status. Returns nil if command execution fails.

    system("unknown command")     #=> nil
    system("echo foo")            #=> true
    system("echo foo | grep bar") #=> false
    

    Furthermore

    An error status is available in $?.

    system("VBoxManage createvm --invalid-option")
    
    $?             #=> #<Process::Status: pid 9926 exit 2>
    $?.exitstatus  #=> 2
    
    0 讨论(0)
  • 2020-12-02 13:30

    system returns false if the command has an non-zero exit code, or nil if there is no command.

    Therefore

    system( "foo" ) or exit
    

    or

    system( "foo" ) or raise "Something went wrong with foo"
    

    should work, and are reasonably concise.

    0 讨论(0)
  • 2020-12-02 13:33

    One way to do this is to chain them using and or &&:

    system("VBoxManage createvm --name test1") and system("ruby test.rb")
    

    The second call won't be run if the first fails.

    You can wrap those in an if () to give you some flow-control:

    if (
      system("VBoxManage createvm --name test1") && 
      system("ruby test.rb")
    ) 
      # do something
    else
      # do something with $?
    end
    
    0 讨论(0)
  • 2020-12-02 13:34

    For me, I preferred use `` to call the shell commands and check $? to get process status. The $? is a process status object, you can get the command's process information from this object, including: status code, execution status, pid, etc.

    Some useful methods of the $? object:

       $?.exitstatus => return error code    
       $?.success? => return true if error code is 0, otherwise false
       $?.pid => created process pid
    
    0 讨论(0)
  • 2020-12-02 13:34

    You're not capturing the result of your system call, which is where the result code is returned:

    exit_code = system("ruby test.rb")
    

    Remember each system call or equivalent, which includes the backtick-method, spawns a new shell, so it's not possible to capture the result of a previous shell's environment. In this case exit_code is true if everything worked out, nil otherwise.

    The popen3 command provides more low-level detail.

    0 讨论(0)
提交回复
热议问题