How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?
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.