我有一个用bash编写的相当健壮和准确的OS检测功能,该功能返回分布和派生(我认为其他人可能会发现它有用)。我现在正在考虑如何最好地处理这些输出,以使脚本可以使用适当的软件包管理器自动选择并安装软件包列表,以进行分发。
我的第一个想法是编写一个临时文件并从那里检查输出,但这似乎是处理它的丑陋方法。接下来,我想到了返回不是特殊含义代码的退出代码和一些if / elif逻辑,而我将不去参加比赛,这也感觉像是一种拙劣的方法来完成这项工作。最终的想法是打印到屏幕上并存储为变量,以再次使用if逻辑。
我在堆栈上滚动浏览了类似的问题,还翻阅了Shell Scripting With Bash手册,希望从中获得一些启发,写出一个干净的解决方案。但是可惜没有火花。
任何见解都会有所帮助。
#!/bin/bash
detect_os()
{
MATCH=`uname -s`
if [ "${MATCH}" = "Linux" ]; then
linux_distro
elif
[ "${MATCH}" = "Darwin" ]; then
printf "DISTRIBUTION=macosx \n"
printf "VERSION=`uname -r` \n"
fi
}
redhat_derivative()
{
local FILE=/etc/redhat-release
grep -i 'red.*hat.*enterprise.*linux' $FILE 2>&1 > /dev/null && { printf "DERIVATIVE=rhel \n"; return; }
grep -i 'red.*hat.*linux' $FILE 2>&1 > /dev/null && { printf "DERIVATIVE=rh \n"; return; }
grep -i 'centos' $FILE 2>&1 > /dev/null && { printf "DERIVATIVE=centos \n"; return; }
grep -i 'fedora' $FILE 2>&1 > /dev/null && { printf "DERIVATIVE=fedora \n"; return; }
printf "DERIVATIVE=unknown \n"
}
debian_derivative()
{
if which lsb_release 2>&1 > /dev/null ; then
printf "DERIVATIVE=`lsb_release --id --short 2> /dev/null` \n"
return
else
printf "DERIVATIVE=unknown \n"
return
fi
}
arch_derivative()
{
local FILE=/etc/os-release
grep -i 'arch' $FILE 2>&1 > /dev/null && { printf "DERIVATIVE=arch \n"; return; }
grep -i 'manjaro' $FILE 2>&1 > /dev/null && { printf "DERIVATIVE=manjaro \n"; return; }
printf "DERIVATIVE=unknown \n"
}
linux_distro()
{
if [ -f /etc/redhat-release ]; then
printf "DISTRIBUTION=redhat \n"
redhat_derivative
elif [ -f /etc/debian_version ]; then
printf "DISTRIBUTION=debian \n"
debian_derivative
elif [ -f /etc/arch-release ]; then
printf "DISTRIBUTION=arch \n"
arch_derivative
fi
}
答案 0 :(得分:1)
我的个人shell库中有两个(相似)版本(一个用于bash,另一个用于不友好的POSIX shell(我在看你破折号。))我检查/ etc / issue中的Linux版本,(大致)这个:
#!/bin/sh
########
## OS ##
########
os () {
ISSUE="$(cat /etc/issue)"
if [ "$(grep -iE 'centos|redhat|yellowdog' /etc/issue)" ]; then
echo ${ISSUE%% *}
elif [ "$(grep -iE 'debian|ubuntu' /etc/issue)" ]; then
echo ${ISSUE%% *}
fi
}
###############
## installer ##
###############
installer () {
OS=$(os)
if [ "$OS" ]; then
if [ "$OS" = 'Debian' ] || [ "$OS" = 'Ubuntu' ]; then
echo 'apt-get install -y'
return 0
elif [ "$OS" = 'Gentoo' ]; then
echo 'emerge'
elif [ "$OS" = 'CentOS' ] || [ "$OS" = 'Redhat' ]; then
echo 'yum install -y'
fi
fi
}
#############
## install ##
#############
#
# generalises automation of install
# in an OS independent way.
# i.e. if Debian, CentOS, Gentoo, Slackware, FreeBDS, OpenSolaris
# this will find a way to install ALL of $@
#
install() {
eval $(which sudo) $(installer) $1
[ "$?" -gt 0 ] && echo "Failed to install $1" >&2 && return 0
return 1
}