2

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).

2

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the answer, but this will not work on Linux will it? My script runs on Windows and Linux.
ok you never mentioned Linux in your question. You are right it will not work on linux as it is. You'll need to modify above code to first find out which OS you're running this script on, you can do this using uname on both windows (provided you have devkit installed, else use systeminfo on windows) as well as linux. After you have identified OS, check win32_process table for windows and ps on linux to find out parent process name.
I'll give this a shot and let you know how I go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.