Search code examples
rubylinuxbashshell

How to continue script execution after a command replaces itself with a new shell process?


I have an executable ruby script as follows:

example:

#!/usr/bin/env ruby
at_exit do
  # Replace the currently running Ruby process with a new instance of the parent shell 
  exec(`ps -p #{Process.ppid} -o comm=`.chomp)
end

It works fine when running as a command, but due to it replacing itself with a new shell instance, it does not work in scripting, as no commands after it are executed.

How do I modify my shell script such that execution continues?

(I am running the shell scripts like so: bash test.sh)

Some examples of what I would like to achieve:

test.sh:

#!/usr/bin/bash
./example && echo "How do i get here"

test1.sh:

#!/usr/bin/bash
VAR=foo
$VAR ./example <argument> 

test2.sh:

#!/usr/bin/bash
cd ~ && git clone https://github.com/gfxstrand/pycook
yes | ./example 

test3.sh:

#!/usr/bin/bash
./example || echo "How do i get here"

Note that I cannot change the behavior of the ruby script-- it must replace itself with a new instance of the parent shell at exit. (The exception to this is a solution replacing the parent process of the ruby script with a new instance of the parent shell, which would also suffice)


Solution

  • Perhaps not the simplest solution, but

    (sh -c ./example & wait)
    

    should work. After example replaces itself with the parent sh process, this process will then immediately end, and the grand parent won't be bothered.