Bash脚本以字符串形式获取操作系统+版本 [英] Bash Script to Get Operating System + Version as string
问题描述
我想制作一个bash脚本,以将系统os和版本作为简单的字符串.
I want to make a bash script to take the system os and the version as a simple string.
获取这些信息的可能方法是
Possible ways to get these info is from
- /etc/issue
- cat/etc/*-release
- lsb_release -a
,也许还有一些我不知道的其他东西.问题是我希望bash脚本能在Ubuntu 12,13,14和CentOS上运行.上述某些功能在这些系统中不起作用.例如,lsb_release在CentOS上不起作用,有时/etc/issue为空,所以我对此不太困惑.
and probably some others which i dont know. The problem is that i want the bash script to work on Ubuntu 12,13,14 and CentOS. Some of the above does not work in these systems. For example the lsb_release does not work on CentOS and sometimes the /etc/issue is empty so i'm little confused about it.
至于字符串,我想以这种方式获取(并将其保存到var).我会举一些例子.
As for the string i want to get it in this way (and save it to var). I will give examples.
如果操作系统是Ubuntu 12.x ,我想将其作为 ubuntu12
如果操作系统是Ubuntu 13.x ,我想将其作为 ubuntu13
If OS is Ubuntu 13.x i want to take it as ubuntu13
如果操作系统是CentOS 7.x ,我想将其作为 centos7
If OS is CentOS 7.x i want to take it as centos7
那么简单吗?
谢谢
推荐答案
这是一个bash解决方案.我在Ubuntu上进行了测试,但未在CentOS上进行过测试(我现在只有RHEL可用).但是您可以测试CentOS部件并根据需要进行修改.
Here is a bash solution. I tested on Ubuntu, but not on CentOS (I only have RHEL available now). But you can test the CentOS part and modify as needed.
#!/usr/bin/env bash
RELEASE=unknown
version=$( lsb_release -r | grep -oP "[0-9]+" | head -1 )
if lsb_release -d | grep -q "CentOS"; then
RELEASE=centos$version
elif lsb_release -d | grep -q "Ubuntu"; then
RELEASE=ubuntu$version
fi
echo $RELEASE
或者,在CentOS上没有lsb_release
:
Or, without lsb_release
on CentOS:
#!/usr/bin/env bash
RELEASE=unknown
if [ -f /etc/redhat-release ]; then
version=$( cat /etc/redhat-release | grep -oP "[0-9]+" | head -1 )
RELEASE=centos$version
elif [ -n $(which lsb_release 2> /dev/null) ] && lsb_release -d | grep -q "Ubuntu"; then
version=$( lsb_release -d | grep -oP "[0-9]+" | head -1 )
RELEASE=ubuntu$version
fi
echo $RELEASE
在任何情况下,都可以用多种方法为这只猫剥皮.
In any case, there's more than one way to skin this cat.
这篇关于Bash脚本以字符串形式获取操作系统+版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!