Method: Utilities#execute_shell

Defined in:
lib/utilities.rb

#execute_shell(command, sensitive_data = nil) ⇒ Object

Executes a command via shell

Attributes

  • command - command to execute on command line

Returns

  • command_run hash => <results>, stderr => any errors, pid => process id, status => exit_code



49
50
51
52
53
54
55
56
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
# File 'lib/utilities.rb', line 49

def execute_shell(command, sensitive_data = nil)
  escaped_command = command.gsub("\\", "\\\\")

  loggable_command = BrpmAuto.privatize(escaped_command, sensitive_data)
  BrpmAuto.log "Executing '#{loggable_command}'..."

  cmd_result = {"stdout" => "","stderr" => "", "pid" => "", "status" => 1}

  output_dir = File.join(BrpmAuto.params.output_dir,"#{precision_timestamp}")
  errfile = "#{output_dir}_stderr.txt"
  complete_command = "#{escaped_command} 2>#{errfile}" unless is_windows?
  fil = File.open(errfile, "w+")
  fil.close

  begin
    cmd_result["stdout"] = `#{complete_command}`
    status = $?
    cmd_result["pid"] = status.pid
    cmd_result["status"] = status.to_i

    fil = File.open(errfile)
    stderr = fil.read
    fil.close

    if stderr.length > 2
      BrpmAuto.log "Command generated an error: #{stderr}"
      cmd_result["stderr"] = stderr
    end
  rescue Exception => e
    BrpmAuto.log "Command generated an error: #{e.message}"
    BrpmAuto.log "Back trace:\n#{e.backtrace}"

    cmd_result["status"] = -1
    cmd_result["stderr"] = "ERROR\n#{e.message}"
  end

  File.delete(errfile)

  cmd_result
end