可以通过以下几种常用命令快速判断 Linux 发行版是 Ubuntu 还是 CentOS:
方法一:查看 /etc/os-release(推荐,通用性强)
cat /etc/os-release
- Ubuntu 输出中会包含
ID=ubuntu或ID_LIKE=debian - CentOS 输出中通常有
ID=centos、ID_LIKE=rhel fedora,或版本信息如VERSION_ID="7"等
示例对比:
# Ubuntu
PRETTY_NAME="Ubuntu 22.04.3 LTS"
NAME="Ubuntu"
ID=ubuntu
...
# CentOS 7
NAME="CentOS Linux"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
...
✅ 适用于大多数现代 Linux 发行版(包括 Ubuntu、CentOS Stream、RHEL、Debian 等)
方法二:检查特定文件是否存在
# 若存在 /etc/lsb-release,通常是 Debian/Ubuntu 系
[ -f /etc/lsb-release ] && cat /etc/lsb-release
# 若存在 /etc/redhat-release,通常是 RHEL/CentOS/Fedora 系
[ -f /etc/redhat-release ] && cat /etc/redhat-release
- Ubuntu 一般没有
/etc/redhat-release - CentOS/RHEL 通常有
/etc/redhat-release
方法三:使用 hostnamectl(需 systemd,较新系统)
hostnamectl | grep "Operating System"
输出会直接显示类似:
Operating System: Ubuntu 22.04.3 LTSOperating System: CentOS Linux 7 (Core)
一键判断脚本示例
if [ -f /etc/os-release ]; then
source /etc/os-release
case "$ID" in
ubuntu) echo "✅ 这是 Ubuntu ($VERSION_ID)" ;;
centos|centos-stream) echo "✅ 这是 CentOS ($VERSION_ID)" ;;
*) echo "ℹ️ 未知发行版: $NAME ($ID)" ;;
esac
else
if [ -f /etc/redhat-release ]; then
echo "✅ 可能是 CentOS/RHEL: $(cat /etc/redhat-release)"
elif [ -f /etc/debian_version ]; then
echo "✅ 可能是 Debian/Ubuntu: $(cat /etc/debian_version)"
else
echo "❌ 无法确定发行版"
fi
fi
💡 提示:在容器环境(如 Docker)中,某些文件可能缺失,建议优先使用
/etc/os-release。
CLOUD技术笔记