bash and if 有多个逻辑操作数

bash and if with multiple logical operands

我正在尝试检查 bash 中的 2 个变量是否为空或未同时定义。如果是这样,则不会更改任何用户密码。

#!/bin/bash
while true
do
    read -s  -p "Enter root password: " rootpass1
    echo
    read -s  -p "Enter root password again: " rootpass2
    echo
    if  [[-z "$rootpass1"] && [-z "$rootpass2"]]
    then
         echo "Password will not be changed"
         break
    else
        if [ $rootpass1 != $rootpass2 ]
        then
            echo "Passwords are not identical"
        else
            echo "user:$rootpass1" | chpasswd
            break
        fi
    fi
done

但我收到以下错误:

script.sh: line 8: [: missing `]'

有线索吗?

怎么样

#!/bin/bash
read -s  -p "Enter root password: " rootpass1
echo
read -s  -p "Enter root password again: " rootpass2
echo

if  [[ -z "$rootpass1" && -z "$rootpass2" ]]
then
    echo "Password will not be changed"
else
    if [[ "$rootpass1" != "$rootpass2" ]]
    then
        echo "Passwords are not identical"
    else
        echo "user:$rootpass1" | chpasswd
    fi
fi

请注意 [[]] 周围的空格很重要。我还认为 || 对于您的第一次测试会好一点:如果 密码为空,则不要做任何事情(因为它们都是空的,或者它们不相同,所以你省点力气)。

两个测试都需要双括号,如下所示:

if  [[ -z "$rootpass1" ]] && [[ -z "$rootpass2" ]]

我根据建议更正了脚本,它确实有效!!! 谢谢 !!!当我能做到的时候,我会为此打分。

#!/bin/bash
while true
do
    read -s  -p "Enter admin password: " rootpass1
    echo
    read -s  -p "Enter admin password again: " rootpass2
    echo
    if  [[ -z "$rootpass1" ]] && [[ -z "$rootpass2" ]]
    then
        echo "Password will not be changed. Both are empty."
        echo
        break
    else
        if [[ $rootpass1 != $rootpass2 ]]
        then
                echo "Passwords are not identical. Try again."
                echo
        else
                echo "root:$rootpass1" | chpasswd
                echo "Password changed."
                echo
                break
        fi
    fi
done