-1

Say I have a web application, with some sort of system execution. I'm going to use Ruby for this example. This app could be portable and installed on either a Windows or Unix server. If the app uses system commands, is there a way to distinguish what platform the server is, then maybe catch in an if statement?

Theoretically like this:

os_check = `checkos` # System ticks to execute through the shell
                     # using fake command

if os_check == 'unix'
  # Run Unix Commands
  `ls -la`
else if os_check == 'dos'
  # Run DOS commands
  `dir`
else
  puts 'OS not detectable'
end

EDIT

I'm not looking for Ruby specifically (removed the tag). That was an example. I was hoping for a shell command that could execute in both environments and be variable based on what the OS is. I actually have to replicate this sort of function in several languages. Sorry for any confusion.

Kyle Macey
  • 8,074
  • 2
  • 38
  • 78
  • possible duplicate of [Ruby How to determine execution environment](http://stackoverflow.com/questions/6523038/ruby-how-to-determine-execution-environment) – gpojd May 09 '12 at 20:55
  • @gpojd Negative. Not looking for a Ruby-only answer. – Kyle Macey May 09 '12 at 21:05
  • @KyleMacey: what is your target technology? Each language is likely to have its own way of detecting the host Operating System; I doubt that there is a technique that works universally. – maerics May 09 '12 at 21:16
  • @maerics Well I was thinking something along the lines of testing `cd /opt` which would only work in Unix. Or even `ping` responds differently in both platforms. – Kyle Macey May 09 '12 at 21:24

3 Answers3

1

Try checking the RUBY_PLATFORM global constant:

case RUBY_PLATFORM
  when /win32/ then # Windows, use "dir"
  # when /darwin/ then # Mac OS X
  # when /linux/ then # Linux
  else # Assume "ls" on all other platforms
end

[Edit] Per your updated question, you might be able to issue the system command echo /? and parse the output to determine the host OS. The "echo" command should exist on most systems but Windows interprets the /? switch as the "help" message whereas UNIX OSes simply echo those characters. For example (again in Ruby, just to demonstrate the general strategy):

def detect_host_operating_system
  (%x{echo /?} =~ /^\/\?\r?\n$/) ? 'unix' : 'windows'
end
maerics
  • 151,642
  • 46
  • 269
  • 291
1

Keep it simple. Try running a command that only exists on the desired platform

dos: cmd

nix: man

The result status of some trival run with no arguments is the key here.

With this method there is no string parsing. Which is more optimized.

0

You can try to do it with Python, this scripting language is installed by default on most Linux distributions and Mac (I think also on Unix systems like BSD, but I am not completely sure about that).

import os

if (os.name == "posix"):
    #run unix command
else:
    #run Windows command

You can also add more OS checks if you like, of course.

Gladen
  • 792
  • 2
  • 8
  • 17