bash和如果有多个逻辑操作数

时间:2015-08-30 00:02:07

标签: bash if-statement conditional-statements logical-operators

我试图在bash中检查2个变量是否为空或同时未定义。如果是这种情况,则不会更改用户密码。

var myElem = $("#childDiv");
console.log(myElem.css('float')); // = left, as defined in the CSS
myElem.wrap('<div class="container"></div>');
console.log(myElem.css('float')); // = none, Why?

但是我收到以下错误:

#!/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

有任何线索吗?

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

怎么样

#!/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

请注意,[[]]周围的空格非常重要。我还认为||对你的第一次测试来说会更好一点:如果 的密码是空的,那就不要做任何事情(因为它们都是空的,或者它们不相同,所以你不遗余力。)

答案 2 :(得分:0)

我用sugestions纠正了脚本,它确实有效! 谢谢 !!!当我能够做到这一点时,我会给予分数。

#!/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