How to call shell commands from Ruby

前端 未结 20 2052
旧时难觅i
旧时难觅i 2020-11-22 01:10

How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?

20条回答
  •  难免孤独
    2020-11-22 01:45

    One more option:

    When you:

    • need stderr as well as stdout
    • can't/won't use Open3/Open4 (they throw exceptions in NetBeans on my Mac, no idea why)

    You can use shell redirection:

    puts %x[cat bogus.txt].inspect
      => ""
    
    puts %x[cat bogus.txt 2>&1].inspect
      => "cat: bogus.txt: No such file or directory\n"
    

    The 2>&1 syntax works across Linux, Mac and Windows since the early days of MS-DOS.

提交回复
热议问题