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?
Below it's an approach to detect Debian and RedHat based Linux OS making use of the /etc/lsb-release and /etc/os-release (depending on the Linux flavor you're using) and take a simple action based on it.
Output example for Ubuntu Linux:
I tend to keep my .bashrc and .bash_alias on a file share that all platforms can access. This is how I conquer the problem in my .bash_alias:
And I have for example a .bash_alias_Linux with:
This way I keep platform specific and portable code separate, you can do the same for .bashrc
I would suggest avoiding some of these answers. Don't forget that you can choose other forms of string comparison, which would clear up most of the variations, or ugly code offered.
One such solution would be a simple check, such as:
if [[ "$OSTYPE" =~ ^darwin ]]; then
Which has the added benefit of matching any version of Darwin, despite it's version suffix. This also works for any variations of
Linux
one may expect.You can see some additional examples within my dotfiles here