Skip to content

Instantly share code, notes, and snippets.

@zimbatm
Created July 23, 2010 07:57
Show Gist options
  • Save zimbatm/487157 to your computer and use it in GitHub Desktop.
Save zimbatm/487157 to your computer and use it in GitHub Desktop.
Temporary disable $stdout
/* Temporary disable $stdout
============================
This method works for Ruby and new sub-processes.
I have seen other techniques on the net which re-assign $stdout with another IO,
but then the sub-processes will still use the old stdout.
*/
def dev_null(&block)
begin
orig_stdout = $stdout.dup # does a dup2() internally
$stdout.reopen('/dev/null', 'w')
yield
ensure
$stdout.reopen(orig_stdout)
end
end
#
# And now, the same for POSIX shells. Got help from http://tldp.org/LDP/abs/html/io-redirection.html
#
dev_null () {
# FIXME: how do we know if 3 is taken ?
exec 3>&1
exec 1>/dev/null
$@
exec 1>&3
exec 3>&- # closes fd3, which is done by GC in ruby
}
# Forget this, in bash you can just redirect the output on the command :
dev_null () {
$@ >/dev/null
}
@merqlove
Copy link

Shortened.

  def dev_null
    orig_stdout = $stdout.dup # does a dup2() internally
    $stdout.reopen('/dev/null', 'w')
    yield
  ensure
    $stdout.reopen(orig_stdout)
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment