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?
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.
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 $?
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With