Detect operating system in shell script

$OSTYPE

You can simply use the pre-defined $OSTYPE variable e.g.:

case "$OSTYPE" in
  solaris*) echo "SOLARIS" ;;
  darwin*)  echo "OSX" ;; 
  linux*)   echo "LINUX" ;;
  bsd*)     echo "BSD" ;;
  msys*)    echo "WINDOWS" ;;
  *)        echo "unknown: $OSTYPE" ;;
esac

However it’s not recognized by the older shells (such as Bourne shell).

This can also be shortened for specific use cases:

if [[ "$OSTYPE" =~ ^darwin ]]; then
    brew install <some-package>
fi

if [[ "$OSTYPE" =~ ^linux ]]; then
    sudo apt-get install <some-package>
fi

Note there’s also $HOSTTYPE which returns the architecture, e.g. x86_64.

uname

Another method is to detect platform based on uname command.

See the following script (ready to include in .bashrc):

# Detect the platform (similar to $OSTYPE)
OS="`uname`"
case $OS in
  'Linux')
    OS='Linux'
    alias ls='ls --color=auto'
    ;;
  'FreeBSD')
    OS='FreeBSD'
    alias ls='ls -G'
    ;;
  'WindowsNT')
    OS='Windows'
    ;;
  'Darwin') 
    OS='Mac'
    ;;
  'SunOS')
    OS='Solaris'
    ;;
  'AIX') ;;
  *) ;;
esac

You can find some practical examples in this .bashrc.

Here is similar version used on Travis CI:

    case $(uname | tr '[:upper:]' '[:lower:]') in
      linux*)
        export TRAVIS_OS_NAME=linux
        ;;
      darwin*)
        export TRAVIS_OS_NAME=osx
        ;;
      msys*)
        export TRAVIS_OS_NAME=windows
        ;;
      *)
        export TRAVIS_OS_NAME=notset
        ;;
    esac