Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if running in Cygwin, Mac or Linux?

I have a shell script that is used both on Windows/Cygwin and Mac and Linux. It needs slightly different variables for each versions.

How can a shell/bash script detect whether it is running in Cygwin, on a Mac or in Linux?

like image 561
bastibe Avatar asked Aug 12 '10 09:08

bastibe


People also ask

Are Mac and Linux commands the same?

In general, both will have the same core commands and features (especially those defined in the Posix standard), but a lot of extensions will be different. For example, linux systems generally have a useradd command to create new users, but OS X doesn't.

How do I check my bash version Mac?

Find bash shell version using the --version option Just pass the --version to the bash command to show version information for this instance of bash shell on the screen and exit successfully: bash --version echo $?


1 Answers

Usually, uname with its various options will tell you what environment you're running in:

pax> uname -a CYGWIN_NT-5.1 IBM-L3F3936 1.5.25(0.156/4/2) 2008-06-12 19:34 i686 Cygwin  pax> uname -s CYGWIN_NT-5.1 

And, according to the very helpful schot (in the comments), uname -s gives Darwin for OSX and Linux for Linux, while my Cygwin gives CYGWIN_NT-5.1. But you may have to experiment with all sorts of different versions.

So the bash code to do such a check would be along the lines of:

unameOut="$(uname -s)" case "${unameOut}" in     Linux*)     machine=Linux;;     Darwin*)    machine=Mac;;     CYGWIN*)    machine=Cygwin;;     MINGW*)     machine=MinGw;;     *)          machine="UNKNOWN:${unameOut}" esac echo ${machine} 

Note that I'm assuming here that you're actually running within CygWin (the bash shell of it) so paths should already be correctly set up. As one commenter notes, you can run the bash program, passing the script, from cmd itself and this may result in the paths not being set up as needed.

If you are doing that, it's your responsibility to ensure the correct executables (i.e., the CygWin ones) are being called, possibly by modifying the path beforehand or fully specifying the executable locations (e.g., /c/cygwin/bin/uname).

like image 146
paxdiablo Avatar answered Oct 21 '22 08:10

paxdiablo