Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

1 snippets
  • How to detect OS in bash script?

    #!/bin/bash
    
    die()
    {
        echo "ERROR: $*" >&2
        exit 1
    }
    
    detect_os ()
    {
        OS="$(uname -s)"
        ARCH="$(uname -m)"
    
        case "$OS" in
            Linux)
                if [ -e /etc/lsb-release ]; then
                    source /etc/lsb-release
    
                    DIST_ID="${DISTRIB_ID}"
                    OS_VERSION="${DISTRIB_RELEASE}"
                    OS_CODENAME="${DISTRIB_CODENAME}"
                elif [ -e /etc/os-release]; then
                    source /etc/os-release
    
                    DIST_ID="${ID}"
                    OS_VERSION="${VERSION_ID}"
                    OS_CODENAME="${VERSION_CODENAME}"
    
                elif [ $(which lsb_release 2>/dev/null) ]; then
                    DIST_ID="$(lsb_release -s -i)"
                    OS_VERSION="$(lsb_release -s -r)"
                    OS_CODENAME="$(lsb_release -s -c)"
                else
                    die "Colud not get OS information"
                fi
    
                case "$DIST_ID" in
                    RedHat*)
                        OS_NAME="RedHat" ;;
                    debian)
                        OS_NAME="Debian" ;;
                    *)
                        OS_NAME="${DIST_ID}" ;;
                esac
                ;;
            *)
                die "Unsupported OS family: $OS"
                ;;
        esac
    
        echo "${OS}"
        echo "${OS_NAME}"
        echo "${OS_VERSION}"
        echo "${OS_CODENAME}"
    }

    This script returns OS information such as type, name, codename and version. It supports the following Linux distributions: Ubuntu, Debian, CentOS, RedHat. If you want to add support for other distributions, write in the comments below.