I would like to keep my .bashrc
and .bash_login
files in version control so that I can use them between all the computers I use. The problem is I have some OS specific aliases so I was looking for a way to determine if the script is running on Mac OS X, Linux or Cygwin.
What is the proper way to detect the operating system in a Bash script?
I think the following should work. I'm not sure about
win32
though.or
if you want more information
I wrote a personal Bash library and scripting framework that uses GNU shtool to do a rather accurate platform detection.
GNU shtool is a very portable set of scripts that contains, among other useful things, the 'shtool platform' command. Here is the output of:
on a few different machines:
This produces pretty satisfactory results, as you can see. GNU shtool is a little slow, so I actually store and update the platform identification in a file on the system that my scripts call. It's my framework, so that works for me, but your mileage may vary.
Now, you'll have to find a way to package shtool with your scripts, but it's not a hard exercise. You can always fall back on uname output, also.
EDIT:
I missed the post by Teddy about
config.guess
(somehow). These are very similar scripts, but not the same. I personally use shtool for other uses as well, and it has been working quite well for me.I tried the above messages across a few Linux distros and found the following to work best for me. It’s a short, concise exact word answer that works for Bash on Windows as well.
Detecting operating system and CPU type is not so easy to do portably. I have a
sh
script of about 100 lines that works across a very wide variety of Unix platforms: any system I have used since 1988.The key elements are
uname -p
is processor type but is usuallyunknown
on modern Unix platforms.uname -m
will give the "machine hardware name" on some Unix systems./bin/arch
, if it exists, will usually give the type of processor.uname
with no arguments will name the operating system.Eventually you will have to think about the distinctions between platforms and how fine you want to make them. For example, just to keep things simple, I treat
i386
throughi686
, any "Pentium*
" and any "AMD*Athlon*
" all asx86
.My
~/.profile
runs an a script at startup which sets one variable to a string indicating the combination of CPU and operating system. I have platform-specificbin
,man
,lib
, andinclude
directories that get set up based on that. Then I set a boatload of environment variables. So for example, a shell script to reformat mail can call, e.g.,$LIB/mailfmt
which is a platform-specific executable binary.If you want to cut corners,
uname -m
and plainuname
will tell you what you want to know on many platforms. Add other stuff when you need it. (And usecase
, not nestedif
!)This checks a bunch of
known
files to identfy if the linux distro is Debian or Ubunu, then it defaults to the$OSTYPE
variable.