How to call shell commands from Ruby

前端 未结 20 2355
旧时难觅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:59

    We can achieve it in multiple ways.

    Using Kernel#exec, nothing after this command is executed:

    exec('ls ~')
    

    Using backticks or %x

    `ls ~`
    => "Applications\nDesktop\nDocuments"
    %x(ls ~)
    => "Applications\nDesktop\nDocuments"
    

    Using Kernel#system command, returns true if successful, false if unsuccessful and returns nil if command execution fails:

    system('ls ~')
    => true
    

提交回复
热议问题