Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run multiple commands in the same shell process

Tags:

shell

ruby

I'm attempting to run a series of commands through Ruby, and capture stdin, stdout, stderr and the exitstatus.

require "open3"
require "pp"

command_list = [
  "export MY_ENV_VAR=foobar",
  "printenv MY_ENV_VAR"
]

executed_commands = []
result = nil

command_list.each do |command|
  stdout, stderr, status = Open3.capture3(command)
  result = status.exitstatus
  executed_commands << [command, stdout, stderr, result]
  break if result != 0
end

pp executed_commands
puts "exited with #{result} exit status."

This process exits with a non-zero status, indicating that the printenv MY_ENV_VAR command fails, and that the commands are not being run in the same process.

How can I execute a series of commands in a single shell process, recording stdin, stdout, stderr and the exitstatus of each command?

like image 656
Richard Avatar asked Dec 09 '25 10:12

Richard


1 Answers

I would strongly suggest you don't chain together multiple shell commands into a single system call if you don't absolutely have to. A major caveat is that you can't individually inspect the return codes of each command in the chain. This leads to lack of control over the command flow. For example, if the first command in the chain fails for any reason, the subsequent commands will still attempt to execute regardless of the state of the first command. This may be undesirable.

I suggest encapsulating the popen functionality into a method and just call the method for each command you want to run. This would allow you to react to any failed execution on a command-by-command basis.

like image 114
Jakir00 Avatar answered Dec 11 '25 00:12

Jakir00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!