如何查看Linux发行版本是Ubuntu还是CentOS
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
-
Use
/etc/os-release
awk -F= '/^NAME/{print $2}' /etc/os-release
-
Use the
lsb_release
tools if availablelsb_release -d | awk -F"\t" '{print $2}'
-
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/
.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
2020-04-12 笔记TODO