在 Linux 系统中,可以通过多种方式判断当前系统是 Ubuntu、CentOS、RedHat 还是其他发行版。以下是一些常用的方法:
✅ 方法一:查看 /etc/os-release 文件(推荐)
这是最标准、通用的方法,适用于大多数现代 Linux 发行版。
cat /etc/os-release
输出示例:
-
Ubuntu:
NAME="Ubuntu" VERSION="22.04.3 LTS (Jammy Jellyfish)" ID=ubuntu ID_LIKE=debian ... -
CentOS Stream:
NAME="CentOS Stream" VERSION="8" ID="centos" ID_LIKE="rhel fedora" ... -
Red Hat Enterprise Linux (RHEL):
NAME="Red Hat Enterprise Linux" VERSION="8.8 (Ootpa)" ID="rhel" ...
重点关注 NAME、ID 和 VERSION 字段。
✅ 方法二:查看 /etc/issue 文件
这个文件通常包含登录前显示的系统信息。
cat /etc/issue
输出可能类似于:
Ubuntu 22.04.3 LTS n l
✅ 方法三:使用 lsb_release 命令(适用于 LSB 兼容系统,如 Ubuntu、Debian)
lsb_release -a
输出示例(Ubuntu):
Distributor ID: Ubuntu
Description: Ubuntu 22.04.3 LTS
Release: 22.04
Codename: jammy
⚠️ 注意:某些最小化安装的 CentOS/RHEL 可能未安装
lsb_release,可运行yum install redhat-lsb-core或dnf install redhat-lsb-core来安装。
✅ 方法四:查看特定发行版的标识文件
对于 RedHat / CentOS / RHEL:
cat /etc/redhat-release
输出示例:
- CentOS 7:
CentOS Linux release 7.9.2009 (Core) - RHEL:
Red Hat Enterprise Linux release 8.8 (Ootpa)
注意:从 CentOS Stream 开始,这个文件可能被
/etc/os-release替代或内容不同。
✅ 方法五:使用 hostnamectl 命令(systemd 系统支持)
hostnamectl
输出中会包含操作系统信息,例如:
Operating System: Ubuntu 22.04.3 LTS
Kernel: Linux 5.15.0-86-generic
Architecture: x86-64
✅ 方法六:通过包管理器判断(间接方法)
| 包管理器 | 对应发行版 |
|---|---|
apt, apt-get |
Ubuntu, Debian |
yum 或 dnf |
CentOS, RHEL, Fedora |
zypper |
SUSE/openSUSE |
pacman |
Arch Linux |
你可以运行:
which apt yum dnf zypper pacman | grep -v "no"
看哪个包管理器存在。
🧪 示例判断脚本(简单判断)
if [ -f /etc/os-release ]; then
. /etc/os-release
echo "系统是: $NAME ($VERSION_ID)"
elif [ -f /etc/redhat-release ]; then
echo "系统是: $(cat /etc/redhat-release)"
elif [ -f /etc/lsb-release ]; then
echo "系统是: $(grep DISTRIB_DESCRIPTION /etc/lsb-release | cut -d= -f2)"
else
echo "无法识别系统类型"
fi
总结推荐顺序:
cat /etc/os-release—— 最准确、通用hostnamectl—— 简洁直观cat /etc/redhat-release—— 针对 RHEL/CentOSlsb_release -a—— 针对 Ubuntu/Debian
如果你告诉我你执行某个命令的输出,我也可以帮你判断具体是哪个系统 😊
ECLOUD博客