thegreendroid
thegreendroid

Reputation: 3328

How do I determine shell execution context of a Ruby script?

Is there a way to programmatically determine if a Ruby script is being run from the Windows DOS shell, Linux bash shell etc.?

I am trying to emit ANSI colour codes on any console that supports it. I have used the term-ansicolor gem along with win32console to translate ANSI colour codes to native Windows command line colour sequences. However, I have found this solution to be quite flaky.

I want to emit ANSI on ANSI-capable consoles only (note this script is run on Windows and Linux with various alternate third-party shells).

Upvotes: 2

Views: 337

Answers (1)

saihgala
saihgala

Reputation: 5774

You could use parent process id to determine where it was started from. You can get parent process id using Process module. However beware of this warning (Returns untrustworthy value on Win32/64.) on Process.ppid, you'll need to thoroughly test this solution. Once you have parent process id, you do a lookup on win32_process table to get the name of process and just check if its cmd.exe. Sample code below.

require 'win32ole'

wmi = WIN32OLE.connect("winmgmts://")
processes = wmi.ExecQuery("select * from win32_process where ProcessId = #{Process.ppid}")

processes.each do |process|
    if process.Name == "cmd.exe"
        puts "started from command prompt. Do something"
    else
        puts "started from elsewhere. Do something else"
    end     
end

Upvotes: 1

Related Questions