努力
加油

如何通过系统文件判断Linux发行版是CentOS还是Ubuntu?

在 Linux 运维和自动化脚本中,准确识别发行版是基础中的基础。虽然 lsb_release -a 是个老办法,但在很多精简版或容器环境中可能不可用,或者输出格式不统一。

作为一线工程师,我更倾向于通过读取系统特定的版本标识文件来判断。CentOS 和 Ubuntu 在这方面的文件结构差异非常明显。以下是几种最稳妥、最通用的判断方式,按推荐程度排序:

1. 最通用且权威的方法:读取 /etc/os-release

这是目前 systemd 时代(CentOS 7+ / Ubuntu 16.04+)的事实标准。几乎所有现代 Linux 发行版都包含这个文件,且字段定义规范。

cat /etc/os-release

判断逻辑:

  • CentOS: NAME 字段通常包含 “CentOS” 或 “Red Hat Enterprise Linux”。
  • Ubuntu: NAME 字段一定是 “Ubuntu”。

脚本示例(Bash):

if grep -q "CentOS" /etc/os-release; then
    echo "This is CentOS"
elif grep -q "Ubuntu" /etc/os-release; then
    echo "This is Ubuntu"
else
    echo "Unknown or other distro"
fi

注意:不要只依赖 ID 字段,因为有些定制版可能会修改 ID,但 NAME 字段更具可读性和稳定性。


2. 传统方法:检查特定版本文件

如果环境非常老旧(如 CentOS 6 或 Ubuntu 14.04 之前),/etc/os-release 可能不存在。此时可以回退到各发行版的专属文件。

CentOS (RHEL 系)

  • CentOS 6 及更早: /etc/redhat-release
    cat /etc/redhat-release
    # 输出示例: CentOS release 6.10 (Final)
  • CentOS 7+: 也有 /etc/redhat-release,同时存在 /etc/centos-release
    cat /etc/centos-release
    # 输出示例: CentOS Linux release 7.9.2009 (Core)

Ubuntu

  • 所有版本: /etc/lsb-release 和 /etc/issue
    cat /etc/lsb-release
    # 输出示例: 
    # DISTRIB_ID=Ubuntu
    # DISTRIB_RELEASE=20.04
    # DISTRIB_CODENAME=focal
    # DISTRIB_DESCRIPTION="Ubuntu 20.04.5 LTS"

综合判断脚本(兼容老版本):

if [ -f /etc/redhat-release ]; then
    DISTRO="CentOS/RHEL"
elif [ -f /etc/centos-release ]; then
    DISTRO="CentOS"
elif [ -f /etc/lsb-release ]; then
    DISTRO="Ubuntu/Debian"
else
    DISTRO="Unknown"
fi

3. 为什么不建议只用 hostnamectl 或 uname?

  • uname -a 只显示内核版本,无法区分发行版(CentOS 和 Ubuntu 都可以跑同一个内核)。
  • hostnamectl 在某些最小化安装或容器中可能信息不全。

4. 实际场景建议:如何写一个健壮的函数?

如果你是在写部署脚本(Ansible, Shell, Python),建议封装一个函数,优先使用 /etc/os-release,并做 fallback:

get_distro_info() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        echo "$ID $VERSION_ID"
    elif [ -f /etc/redhat-release ]; then
        cat /etc/redhat-release
    elif [ -f /etc/lsb-release ]; then
        grep DISTRIB_ID /etc/lsb-release | cut -d= -f2
    else
        echo "unknown"
    fi
}

总结

特征 CentOS Ubuntu
核心标识文件 /etc/os-release, /etc/centos-release, /etc/redhat-release /etc/os-release, /etc/lsb-release
/etc/os-release 中的 ID centos 或 rhel ubuntu
包管理器 yum / dnf apt / apt-get
默认 Shell Bash Bash (Zsh 也可选)

最终结论:
在现代生产环境中,直接解析 /etc/os-release 文件的 ID 或 NAME 字段是最可靠、最标准的方式。它避免了因发行版历史遗留问题导致的误判,也符合 FHS(文件系统层次结构标准)的最新实践。