Skip to content

Instantly share code, notes, and snippets.

@blevonius
Last active January 15, 2016 21:34
Show Gist options
  • Save blevonius/13ce0eaa71fad11f3ac1 to your computer and use it in GitHub Desktop.
Save blevonius/13ce0eaa71fad11f3ac1 to your computer and use it in GitHub Desktop.
call bash from ruby code
require 'posix/spawn' # https://github.com/rtomayko/posix-spawn
require 'shellwords'
# thanks to:
# http://blog.honeybadger.io/capturing-stdout-stderr-from-shell-commands-via-ruby/
# http://greyblake.com/blog/2013/09/21/how-to-call-bash-not-shell-from-ruby/
# https://github.com/rtomayko/posix-spawn
def bash(command)
escaped_command = Shellwords.escape(command)
pid, stdin, stdout, stderr = POSIX::Spawn.popen4("bash -c #{escaped_command}")
begin
stdin.close
result = stdout.read
ensure
exit_code = Process::waitpid2(pid)[1]
stderr_msg = exit_code == 0 ? '' : stderr.read
[stdin, stdout, stderr].each { |io| io.close if !io.closed? }
raise StandardError, "Cmd failed: #{stderr_msg}" if exit_code != 0
end
result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment