运维系列:Shell脚本判断OS版本




Shell脚本判断OS版本

Shell脚本中经常需要对操作系统的版本类型类型进行判断。这里介绍几种常用的方法,如有遗漏请包涵 😃

uname

uname ( short for unix name ) 用来打印系统信息,在shell脚本中可以这样使用:

if [ x`uname`x = xFreeBSDx ]; then
    sudo pkg install -yq \
        devel/git \
        ...
else
    ...

/etc/os-release

Linux发行版中都会有/etc/os-release文件,可以通过source命令将文件中的K/V值引入到上下文中。

CentOS 7:
$ cat /etc/os-release
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"
Ubuntu 16.04:
$ cat /etc/os-release
NAME="Ubuntu"
VERSION="16.04.1 LTS (Xenial Xerus)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 16.04.1 LTS"
VERSION_ID="16.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"
UBUNTU_CODENAME=xenial
在Shell脚本中这样使用:
#!/bin/bash

source /etc/os-release
case $ID in
debian|ubuntu|devuan)
    sudo apt-get install lsb-release
    ;;
centos|fedora|rhel)
    yumdnf="yum"
    if test "$(echo "$VERSION_ID >= 22" | bc)" -ne 0; then
        yumdnf="dnf"
    fi
    sudo $yumdnf install -y redhat-lsb-core
    ;;
*)
    exit 1
    ;;
esac

lsb_release

在上一节的例子中已经将lsb_release ( Linux Standard Base ) 工具安装到系统中,使用方法:

Ubuntu 16.04
$ lsb_release -sc
xenial
CentOS 7
$ lsb_release -si
CentOS
$ lsb_release -rs
7.1.1503
$ lsb_release -rs | cut -f1 -d.
7
$ lsb_release -rs | cut -f2 -d.
1
$ lsb_release -rs | cut -f3 -d.
1503

centos7 安装lsb_release

CentOS 7 使用的是 systemdlsb_release 命令在 systemd 中已经被 rpm 包 redhat-lsb-core 所提供。如果你需要安装 lsb_release,实际上你应该安装的是 redhat-lsb-core

执行以下命令来安装:

sudo yum install redhat-lsb-core

安装完成后,你可以使用 lsb_release -a 来查看系统的 LSBLinux Standard Base)信息。

lsb_release -a

这将显示系统的详细信息,包括发行版的ID版本号描述等。

安装lsb_release

linux系统安装lsb_release

在线安装lsb_release

在线安装lsb_release命令

yum -y install lsb_release

离线安装lsb_release

阿里云镜像地址:
https://developer.aliyun.com/mirror/

说明:根据自己的操作系统和版本号在阿里云镜像网站中下载安装包,此处已centos7为例,经测试发现,centos7系统lsb_release安装包也适用于麒麟系统。在找不到包的情况下,可用centos7的安装包测试(不确定性)。

centos7系统的安装包镜像位置
https://mirrors.aliyun.com/centos/7/os/x86_64/Packages/

下载redhat-lsb-core-4.1-27.el7.centos.1.x86_64.rpm安装包

使用rpm方式安装lsb-core安装包:

rpm -ivh redhat-lsb-core-4.1-27.el7.centos.1.x86_64.rpm







Archive

Shell脚本判断OS版本

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

坦笑&&life

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值