How to call shell commands from Ruby

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

    If you really need Bash, per the note in the "best" answer.

    First, note that when Ruby calls out to a shell, it typically calls /bin/sh, not Bash. Some Bash syntax is not supported by /bin/sh on all systems.

    If you need to use Bash, insert bash -c "your Bash-only command" inside of your desired calling method:

    quick_output = system("ls -la")
    
    quick_bash = system("bash -c 'ls -la'")
    

    To test:

    system("echo $SHELL")
    system('bash -c "echo $SHELL"')
    

    Or if you are running an existing script file like

    script_output = system("./my_script.sh")
    

    Ruby should honor the shebang, but you could always use

    system("bash ./my_script.sh")
    

    to make sure, though there may be a slight overhead from /bin/sh running /bin/bash, you probably won't notice.

提交回复
热议问题