T145
T145

Reputation: 1523

How is the exit command properly executed in Ruby?

I have been trying to create a Ruby gem that simply exits my terminal whenever "x" is entered. Here is my main project file:

module SwissKnife
  VERSION = '0.0.1'

  class ConsoleUtility
    def exit
      `exit`
    end
  end
end

and my executable:

#!/usr/bin/env ruby

require 'swissknife'

util = SwissKnife::ConsoleUtility.new
util.exit

For some reason whenever I run this nothing appears to happen. I debugged it by adding in a simple puts 'Hello World!' in there, and it would print "Hello World!" but not exit. What am I doing wrong? Any help is greatly appreciated!

Upvotes: 0

Views: 66

Answers (1)

Max
Max

Reputation: 22315

  1. Backticks execute code in a new shell
  2. exit isn't an executable that your shell runs, it's a special command understood by your shell - telling it to exit

So when you do

`exit`

it starts a shell which immediately exits. Not very useful. To exit the shell, you can instead kill Ruby's parent process.

Process.kill 'HUP', Process.ppid

Upvotes: 1

Related Questions