如何使用 shell 脚本查找 Linux 分发名称?
How to find Linux Distribution name using shell script?
我正在编写一个 shell 脚本,我需要在其中使用当前操作系统名称才能使其通用。喜欢:
if [ $Operating_System == "CentOS" ]
then
echo "CentOS";
# Do this
elif [ $Operating_System == "Ubuntu" ]
then
echo "Ubuntu";
# Do that
else
echo "Unsupported Operating System";
fi
怎么可能?在 lsb_release -a
命令或其他命令上应用正则表达式?
谢谢..
$ lsb_release -i
Distributor ID: Fedora
$ lsb_release -i | cut -f 2-
Fedora
对于几乎所有 linux 发行版,cat /etc/issue
都可以。
编辑:显然,没有任何解决方案可以适用于所有发行版,因为发行版可以免费随心所欲。
进一步说明:这不能保证有效 - 什么都不会 - 但根据我的经验,这是最常用的方法。实际上,它是 only 方法始终如一地工作(这里提到的 lsb_release
,通常会产生 command not found
)。
我会用 uname -a
robert@debian:/tmp$ uname -a
Linux debian 3.2.0-4-686-pae #1 SMP Debian 3.2.65-1+deb7u2 i686 GNU/Linux
您可以从lsb_release
获取信息:
echo "$(lsb_release -is)"
i
代表分销商id。
s
简称
例如。它显示 Ubuntu
而不是 Distributor Id: Ubuntu
还有其他选项:
-r : release
-d : description
-c : codename
-a : all
您可以通过运行lsb_release --help
或man lsb_release
获取此信息
编辑:
正如 @S0AndS0 所建议的那样,这个稍微好一点:
awk -F'=' '/^ID=/ {print tolower()}' /etc/*-release 2> /dev/null
试试这个:
awk '/^ID=/' /etc/*-release | awk -F'=' '{ print tolower() }'
DISTRO=$( cat /etc/*-release | tr [:upper:] [:lower:] | grep -Poi '(debian|ubuntu|red hat|centos|nameyourdistro)' | uniq )
if [ -z $DISTRO ]; then
DISTRO='unknown'
fi
echo "Detected Linux distribution: $DISTRO"
这是我得到的:
#!/bin/bash
dist=$(tr -s ' 1' '2' < /etc/issue | head -n 1)
check_arch=$(uname -m)
echo "[$green+$txtrst] Distribution Name: $dist"
我正在编写一个 shell 脚本,我需要在其中使用当前操作系统名称才能使其通用。喜欢:
if [ $Operating_System == "CentOS" ]
then
echo "CentOS";
# Do this
elif [ $Operating_System == "Ubuntu" ]
then
echo "Ubuntu";
# Do that
else
echo "Unsupported Operating System";
fi
怎么可能?在 lsb_release -a
命令或其他命令上应用正则表达式?
谢谢..
$ lsb_release -i
Distributor ID: Fedora
$ lsb_release -i | cut -f 2-
Fedora
对于几乎所有 linux 发行版,cat /etc/issue
都可以。
编辑:显然,没有任何解决方案可以适用于所有发行版,因为发行版可以免费随心所欲。
进一步说明:这不能保证有效 - 什么都不会 - 但根据我的经验,这是最常用的方法。实际上,它是 only 方法始终如一地工作(这里提到的 lsb_release
,通常会产生 command not found
)。
我会用 uname -a
robert@debian:/tmp$ uname -a
Linux debian 3.2.0-4-686-pae #1 SMP Debian 3.2.65-1+deb7u2 i686 GNU/Linux
您可以从lsb_release
获取信息:
echo "$(lsb_release -is)"
i
代表分销商id。
s
简称
例如。它显示 Ubuntu
而不是 Distributor Id: Ubuntu
还有其他选项:
-r : release
-d : description
-c : codename
-a : all
您可以通过运行lsb_release --help
或man lsb_release
编辑: 正如 @S0AndS0 所建议的那样,这个稍微好一点:
awk -F'=' '/^ID=/ {print tolower()}' /etc/*-release 2> /dev/null
试试这个:
awk '/^ID=/' /etc/*-release | awk -F'=' '{ print tolower() }'
DISTRO=$( cat /etc/*-release | tr [:upper:] [:lower:] | grep -Poi '(debian|ubuntu|red hat|centos|nameyourdistro)' | uniq )
if [ -z $DISTRO ]; then
DISTRO='unknown'
fi
echo "Detected Linux distribution: $DISTRO"
这是我得到的:
#!/bin/bash
dist=$(tr -s ' 1' '2' < /etc/issue | head -n 1)
check_arch=$(uname -m)
echo "[$green+$txtrst] Distribution Name: $dist"