如何查看Linux发行版本是Ubuntu还是CentOS

 

https://askubuntu.com/questions/459402/how-to-know-if-the-running-platform-is-ubuntu-or-centos-with-help-of-a-bash-scri

 

How to know if the running platform is Ubuntu or CentOS with help of a Bash script?

 

OS_NAME=$(lsb_release -si) 
case "$OS_NAME" in
    CentOS)
    echo CentOS
        ;;
    Ubuntu)
    echo Ubuntu
        ;;
    *)
    echo Others
        ;;
esac

 

 

 

  1. Use /etc/os-release

    awk -F= '/^NAME/{print $2}' /etc/os-release
    
  2. Use the lsb_release tools if available

    lsb_release -d | awk -F"\t" '{print $2}'
    
  3. Use a more complex script that should work for the great majority of distros:

    # Determine OS platform
    UNAME=$(uname | tr "[:upper:]" "[:lower:]")
    # If Linux, try to determine specific distribution
    if [ "$UNAME" == "linux" ]; then
        # If available, use LSB to identify distribution
        if [ -f /etc/lsb-release -o -d /etc/lsb-release.d ]; then
            export DISTRO=$(lsb_release -i | cut -d: -f2 | sed s/'^\t'//)
        # Otherwise, use release info file
        else
            export DISTRO=$(ls -d /etc/[A-Za-z]*[_-][rv]e[lr]* | grep -v "lsb" | cut -d'/' -f3 | cut -d'-' -f1 | cut -d'_' -f1)
        fi
    fi
    # For everything else (or if above failed), just use generic identifier
    [ "$DISTRO" == "" ] && export DISTRO=$UNAME
    unset UNAME

 

 

 

The lsb_release command was added to the Linux Standard Base (ISO/IEC 23360) for this purpose:

$ lsb_release -si
Ubuntu
$ lsb_release -sd
Ubuntu 18.04.3 LTS
$ lsb_release -sr
18.04
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.3 LTS
Release:        18.04
Codename:       bionic

Therefore a case statement along the lines of

case "`/usr/bin/lsb_release -si`" in
  Ubuntu) echo 'This is Ubuntu Linux' ;;
       *) echo 'This is something else' ;; 
esac

should do what you want.

On newer Linux distributions based on systemd there is also /etc/os-release, which is intended to be included into shell scripts with the source (.) command, as in

. /etc/os-release

case "$ID" in
  ubuntu) echo 'This is Ubuntu Linux' ;;
       *) echo 'This is something else' ;; 
esac

But in the use-case example you gave, you may actually be more interested not in the name of the distribution, but whether it has apt-get or yum. You could just test for the presence of the files /usr/bin/apt-get or /usr/bin/yum with if [ -x /usr/bin/apt-get ]; then ... or for the presence of associated infrastructure directories, such as /var/lib/apt and /etc/apt/.

 

posted @ 2023-04-12 09:29  sinferwu  阅读(170)  评论(0编辑  收藏  举报