Last active
January 15, 2016 21:34
-
-
Save blevonius/13ce0eaa71fad11f3ac1 to your computer and use it in GitHub Desktop.
call bash from ruby code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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