7

How to find the operating system using bash script? I found this answer: Detect the OS from a Bash script. It is not clear it would work on Mac OS X.

I would like to find it on Mac OS X vs different linux OS's.

Community
  • 1
  • 1
ssk
  • 9,045
  • 26
  • 96
  • 169
  • 1
    On Mac OS X, `uname` reports `Darwin`, unlike Linux where it reports `Linux`. What more do you need to know? – Jonathan Leffler Feb 06 '16 at 03:16
  • uname -a works find on my Mac. Look at this: http://unix.stackexchange.com/questions/88644/how-to-check-os-and-version-using-a-linux-command – melis Feb 06 '16 at 03:18
  • Thanks for the suggestion. – ssk Feb 06 '16 at 04:09
  • Possible duplicate of [How to detect the OS from a Bash script?](https://stackoverflow.com/q/394230/608639), [How to check if running in Cygwin, Mac or Linux?](https://stackoverflow.com/q/3466166/608639), [uname](https://en.wikipedia.org/wiki/Uname) on Wikipedia, etc. – jww May 20 '19 at 01:13

3 Answers3

10

For Linux you can type in the following bash command:

$ cat /etc/*-release

For Mac OS X you can try one of these commands:

$ sw_vers -productVersion 
$ system_profiler SPSoftwareDataType
anicolae
  • 523
  • 3
  • 6
  • I've found that the following command properly shows me the distro information on Linux just about on everything I tried: `grep -Eh -- "DISTRIB_DESCRIPTION=|PRETTY_NAME=" /etc/*{_version,*-release} 2>/dev/null | cut -d= -f2 | tr -d "\"" | sort -u` – ikaerom Feb 22 '23 at 22:41
7

Derived from other answers, this worked for me:

CURRENT_OS="OSX" #CENTOS, UBUNUTU are other valid options
function findCurrentOSType()
{
    echo "Finding the current os type"
    echo
    osType=$(uname)
    case "$osType" in
            "Darwin")
            {
                echo "Running on Mac OSX."
                CURRENT_OS="OSX"
            } ;;    
            "Linux")
            {
                # If available, use LSB to identify distribution
                if [ -f /etc/lsb-release -o -d /etc/lsb-release.d ]; then
                    DISTRO=$(gawk -F= '/^NAME/{print $2}' /etc/os-release)
                else
                    DISTRO=$(ls -d /etc/[A-Za-z]*[_-][rv]e[lr]* | grep -v "lsb" | cut -d'/' -f3 | cut -d'-' -f1 | cut -d'_' -f1)
                fi
                CURRENT_OS=$(echo $DISTRO | tr 'a-z' 'A-Z')
            } ;;
            *) 
            {
                echo "Unsupported OS, exiting"
                exit
            } ;;
    esac
}
ssk
  • 9,045
  • 26
  • 96
  • 169
5

use uname

$(uname -s)

this will give you the os name (Darwin = OSX)

$(uname -v)

will give you the os version

see uname manual here

Nic Wanavit
  • 2,363
  • 5
  • 19
  • 31