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: {}, loog: Loog::NULL, accept: [0], both: false) ⇒ String

Execute a single bash command.

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

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

Parameters:

  • cmd (String)

    The command to run

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

    Input string

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

    Environment variables

  • loog (Loog) (defaults to: Loog::NULL)

    Logging facility with .debug() method

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

    List of accepted exit codes (accept all if empty)

  • both (Boolean) (defaults to: false)

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

Returns:

  • (String)

    Stdout



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/qbash.rb', line 47

def qbash(cmd, stdin: '', env: {}, loog: Loog::NULL, accept: [0], both: false)
  loog.debug("+ #{cmd}")
  buf = ''
  e = 1
  cmd = cmd.join(' ') if cmd.is_a?(Array)
  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
      loog.debug(ln)
      buf += ln
    end
    e = thr.value.to_i
    raise "The command '#{cmd}' failed with exit code ##{e}\n#{buf}" if !accept.empty? && !accept.include?(e)
  end
  return [buf, e] if both
  buf
end