Answers:
不幸的是,没有确定版本的简单方法。大多数主要的发行版正朝着他们使用一个系统/etc/os-release
来存储这些信息。大多数现代发行版还包含这些lsb_release
工具,但默认情况下并不总是安装这些工具。因此,这里有一些可以使用的方法:
采用 /etc/os-release
awk -F= '/^NAME/{print $2}' /etc/os-release
使用lsb_release
工具(如果有)
lsb_release -d | awk -F"\t" '{print $2}'
使用应该适用于大多数发行版的更复杂的脚本:
# 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
解析以下版本信息gcc
:
CentOS 5.x
$ gcc --version
gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-54)
Copyright (C) 2006 Free Software Foundation, Inc.
CentOS 6.x版
$ gcc --version
gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3)
Copyright (C) 2010 Free Software Foundation, Inc.
Ubuntu 12.04
$ gcc --version
gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation, Inc.
Ubuntu 14.04
$ gcc --version
gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
<—
事实并非如此。 例如,席尔文·皮诺(Sylvain Pineau)展示了一种简单的单行代码,它通过遵循Python来可靠地查询当前平台类型-大多数平台(包括Ubuntu)上已预装了该代码。Shell脚本绝不应尝试使用此答案中实现的这类低级,非便携式测试来手动查询平台元数据。
awk
,mawk
或者其他实现也将同样有效。
lsb_release
以下方法更具体:lsb_release -d | awk -F"\t" '{print $2}' | awk -F " " '{print $1}'
lsb_release -d | awk '{print $3}'
或grep -oP 'VERSION="\K\S+' /etc/os-release
,而无需双管awk。
这是一个简单的答案,我发现仅凭文件的存在即可在所有版本的Ubuntu / CentOS / RHEL上使用(当然,如果有人在您的Ubuntu盒中随机放置/ etc / redhat-release等,则不是故障保护):
if [ -f /etc/redhat-release ]; then
yum update
fi
if [ -f /etc/lsb-release ]; then
apt-get update
fi
/etc/lsb-release
CloudLinux(CentOS)6.8上存在,因此它将同时返回yum
和apt-get
。
使用Chef完成这些任务。;-)
在Chef中,可以使用以下platform?
方法:
if platform?("redhat", "centos", "fedora")
# Code for only Red Hat Linux family systems.
end
要么:
if platform?("ubuntu")
# Code for only Ubuntu systems
end
要么:
if platform?("ubuntu")
# Do Ubuntu things
end
要么:
if platform?("freebsd", "openbsd")
# Do BSD things
end
lsb_release
,/etc/os-release
),该解决方案具有需要厨师的明显的缺点-一个重量级的基础设施即代码(IAC)的框架不是默认情况下在大多数平台上,并要求使用的安装它自己的特定领域语言(DSL)。总之,大多数用户可能只是想推迟到Python,这是默认安装在大多数平台(包括Ubuntu)和接口以及与shell脚本。
以下脚本应说明它是否是Ubuntu。如果不是,而您拥有的唯一其他选择是CentOS,则应在else
子句中使用它:
dist=`grep DISTRIB_ID /etc/*-release | awk -F '=' '{print $2}'`
if [ "$dist" == "Ubuntu" ]; then
echo "ubuntu"
else
echo "not ubuntu"
fi
lsb_release
工具简化该过程,该工具应该读出相同的文件。lsb_release -i
报告Distributor ID: Ubuntu
或Distributor ID: CentOS
在这些情况下。