Module: Kernel

Defined in:
lib/qbash.rb

Overview

Execute one bash command.

Author

Yegor Bugayenko (yegor256@gmail.com)

Copyright

Copyright © 2024 Yegor Bugayenko

License

MIT

Instance Method Summary collapse

Instance Method Details

#qbash(cmd, stdin: '', env: {}, log: Loog::NULL, accept: [0], both: false, timeout: nil) ⇒ String

Execute a single bash command.

For example:

year = qbash('date +%Y')

If exit code is not zero, an exception will be raised.

To escape arguments, use Shellwords.escape() method.

Stderr automatically merges with stdout.

Read this <a href=“github.com/yegor256/qbash”>README</a> file for more details.

Parameters:

  • cmd (String)

    The command to run, for example echo “Hello, world!”

  • stdin (String) (defaults to: '')

    The stdin to provide to the command

  • env (Hash) (defaults to: {})

    Hash of environment variables

  • log (Loog|IO) (defaults to: Loog::NULL)

    Logging facility with .debug() method (or $stdout)

  • accept (Array) (defaults to: [0])

    List of accepted exit codes (accepts all if the list is nil)

  • both (Boolean) (defaults to: false)

    If set to TRUE, the function returns an array (stdout, code)

  • timeout (Integer) (defaults to: nil)

    If it’s set to non-NIL, the execution will fail after this number of seconds

Returns:

  • (String)

    Everything that was printed to the stdout by the command



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/qbash.rb', line 57

def qbash(cmd, stdin: '', env: {}, log: Loog::NULL, accept: [0], both: false, timeout: nil)
  cmd = cmd.join(' ') if cmd.is_a?(Array)
  if log.respond_to?(:debug)
    log.debug("+ #{cmd}")
  else
    log.print("+ #{cmd}\n")
  end
  buf = ''
  e = 1
  start = Time.now
  thread =
    Thread.new do
      Open3.popen2e(env, "/bin/bash -c #{Shellwords.escape(cmd)}") do |sin, sout, thr|
        sin.write(stdin)
        sin.close
        until sout.eof?
          begin
            ln = sout.gets
          rescue IOError => e
            ln = Backtrace.new(e).to_s
          end
          if log.respond_to?(:debug)
            log.debug(ln)
          else
            log.print("#{ln}\n")
          end
          buf += ln
        end
        e = thr.value.to_i
        if !accept.nil? && !accept.include?(e)
          raise "The command '#{cmd}' failed with exit code ##{e} in #{start.ago}\n#{buf}"
        end
      end
    end
  raise "Execution of #{cmd} timed out in #{start.ago}" if thread.join(timeout).nil?
  return [buf, e] if both
  buf
end