提问者:小点点

Bash脚本:如果变量等于字符串[重复]


我对 Bash 脚本很陌生,目前,根据用户的操作系统,我正在努力创建一个安装程序来安装 Docker 客户端和 Docker-Compose。此脚本不打算在每个操作系统上运行,其范围仅适用于 Ubuntu 16.04、18.04、CentOS 7 和 8。

我已经编写了下面的代码来验证用户的操作系统并开始安装过程(目前,我正试图让它适用于Ubuntu 18.04):


################
### Check OS ###
################

if [ -f /etc/os-release ]; then
    # freedesktop.org and systemd
    . /etc/os-release
    OS=$NAME
    VER=$VERSION_ID
    RESULT="$OS $VER"
    printf -v $RESULT "Ubuntu 18.04"
elif type lsb_release >/dev/null 2>&1; then
    # linuxbase.org
    OS=$(lsb_release -si)
    VER=$(lsb_release -sr)
elif [ -f /etc/lsb-release ]; then
    # For some versions of Debian/Ubuntu without lsb_release command
    . /etc/lsb-release
    OS=$DISTRIB_ID
    VER=$DISTRIB_RELEASE
elif [ -f /etc/debian_version ]; then
    # Older Debian/Ubuntu/etc.
    OS=Debian
    VER=$(cat /etc/debian_version)
elif [ -f /etc/SuSe-release ]; then
    # Older SuSE/etc.
    ...
elif [ -f /etc/redhat-release ]; then
    # Older Red Hat, CentOS, etc.
    ...
else
    # Fall back to uname, e.g. "Linux <version>", also works for BSD, etc.
    OS=$(uname -s)
    VER=$(uname -r)
fi

echo $RESULT

#################################
### Ubuntu 18.04 Installation ###
#################################

if [ $RESULT = "Ubuntu 18.04" ]; then

    echo "Installing on Ubuntu 18.04"
    sudo apt update
    sudo apt install apt-transport-https ca-certificates curl software-properties-common -y
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
    sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable"
    sudo apt update
    apt-cache policy docker-ce
    sudo apt install docker-ce
    sudo systemctl status docker
    sudo curl -L https://github.com/docker/compose/releases/download/1.21.2/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
    sudo chmod +x /usr/local/bin/docker-compose
    docker-compose --version

else
    echo "not working"
fi 

在Ubuntu 18.04上运行上述程序的结果如下:

Ubuntu 18.04                                
./test.sh: line 46: [: too many arguments   
not working

如何将$RESULT的输出与字符串进行比较?欢迎提出任何建议或建议!


共1个答案

匿名用户

$RESULT包含空格,请将其引号以避免分词:

if [ "$RESULT" = "Ubuntu 18.04" ]; then

相关问题