【问题标题】:bash and if with multiple logical operandsbash 和 if 有多个逻辑操作数
【发布时间】:2015-08-30 00:02:07
【问题描述】:

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

#!/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 `]'

有什么线索吗?

【问题讨论】:

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


【解决方案1】:

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

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

【讨论】:

  • if [[ -z "$rootpass1" && -z "$rootpass2" ]] 也可以正常工作(在 ksh 中测试)。祝大家好运。
  • 你是对的!它起作用了,所以我用正确的脚本编辑了这个问题。
【解决方案2】:

怎么样

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

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

【讨论】:

  • 对不起!!我是新手,正在学习!!!做了你告诉我的,并在下面发布了我自己的答案!!!谢谢
  • @FedeKrum 没关系,你会及时掌握的:)你只是误解了我,我试图在你的答案下面再次解释。最终我们应该有:1. 您的问题,经过编辑以包含最终解决方案以及原始问题,2. Steve 和我的答案,3. 没有我们健谈的 cmets:) 我'当我们得出最终结论时,我会像这个一样删除我的。
  • @AndrasDeak 不,那是错误的。问题应该只包含问题。接受的答案应该或多或少是 OP 最终使用的答案;有时 OP 会接受其中一个答案,但仍会发布她/他自己的答案,以澄清它是如何改编的。
  • @tripleee,我完全同意,但 OP 似乎坚持以一种或另一种方式包含最终解决方案......我提出的解决方案已经是一种妥协。 (他们最初的解决方案是将问题更改为仅包含最终代码...)
【解决方案3】:

我用建议更正了脚本,它确实有效! 谢谢 !!!当我能够做到这一点时,我会为此加分。

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

【讨论】:

  • 越来越好。您不需要添加自己的答案,因为我已经这样做了:) 但是如果您仍然想包含最终解决方案,请编辑您的原始问题并添加工作代码的最终版本,并进行适当的分隔从原来的问题。您应该在两者之间放置一个有意义的标题。
  • 这在第二个if 中仍然缺乏正确的引用。另见stackoverflow.com/questions/10067266/…
  • 为了保持一致性,您可能希望在任何地方都使用[[,而不是混合使用[[[
猜你喜欢
  • 2013-07-26
  • 2015-10-27
  • 2014-07-03
  • 2018-05-04
  • 1970-01-01
  • 2022-12-20
  • 1970-01-01
  • 1970-01-01
  • 2014-10-31
相关资源
最近更新 更多