I want to make a system calling method that returns output, success rate, and exit status of a system command, like the sys method in the example program below. My system call fails, however, when I put a definition of an environment variable in front of the system command.
It works only if I put &&'s between the envvar definition(s) and the command, as illustrated in the program. But that means that I'll have to interpret the argument of my method to insert those &&'s.
Is there a better way?
#!/usr/bin/env ruby
# return output, success rate, and exit status of a system command
def sys(command)
[%x{#{command} 2>&1}, $?.success?, $?.exitstatus]
end
def pr(command,output,success,status)
puts "command: #{command}"
puts " output: #{output}"
puts "success: #{success ? 'succeeded' : 'failed'}"
puts " status: #{status}",''
end
command = "echo hello"; pr(command,*sys(command))
command = "xxxx hello"; pr(command,*sys(command))
command = "x=hello echo $x"; pr(command,*sys(command)) # FAILS!
command = "x=hello && echo $x"; pr(command,*sys(command))
Outputs:
command: echo hello
output: hello
success: succeeded
status: 0
command: xxxx hello
output: sh: xxxx: command not found
success: failed
status: 127
command: x=hello echo $x
output:
success: succeeded
status: 0
command: x=hello && echo $x
output: hello
success: succeeded
status: 0
···
--
Wybo