巴什:`如果![$ falseSetVar]`不会为我正确评估

den*_*ski 0 bash sh

我在循环中有一个if语句.它最初设置为false,所以我在循环的第一次运行时在文件中插入一个时间戳.

我似乎无法得到以下正确评估.

$ConnectionIsCurrently=false
if ! [ $ConnectionIsCurrently ]; then
    # changing false to true so this only occurs once. 
    $ConnectionIsCurrently=true
fi
Run Code Online (Sandbox Code Playgroud)

这是完整的循环:

while [  $i -le $NoOfTests ]; do
    ping -c1 -t1 www.google.ie > /dev/null
    if [ $? = 0 ]; then
        ConTestPASSCount=$((ConTestPASSCount+1))
        if ! [ $ConnectionIsCurrently ]; then
            printf 'PASSED AT: '
            date "+%s"
            printf 'PASSED AT: ' >> $directory$LogFile
            date "+%s" >> $directory$LogFile
            ConnectionIsCurrently=true
        fi
        echo "PASSCount $ConTestPASSCount"
    else
        ConTestFAILCount=$((ConTestFAILCount+1))
        if [ $ConnectionIsCurrently ]; then
            printf 'FAILED AT: '
            date "+%s"
            printf 'FAILED AT: ' >> $directory$LogFile
            date "+%s" >> $directory$LogFile
            ConnectionIsCurrently=false
        fi
        echo "FAILCount $ConTestFAILCount"
    fi
    sleep 1
    Testcount=$((Testcount+1))
    i=$((i+1))
done
Run Code Online (Sandbox Code Playgroud)

Bar*_*mar 5

shell没有布尔值,它只对字符串(或数字$(()))进行操作.语法:

if [ $ConnectionIsCurrently ]
Run Code Online (Sandbox Code Playgroud)

测试是否$ConnectionIsCurrently为非空字符串,并且"false"不为空.

您可以将空值用作falsey,将任何非空值用作truthy.

ConnectionIsCurrently=
if ! [ "$ConnectionIsCurrently" ]; then
    ConnectionIsCurrently=true
fi
Run Code Online (Sandbox Code Playgroud)

另请注意$,只有在您阅读变量名时,才会在分配变量名之前放置变量名.你通常应该引用变量,除非你确定要完成分词.当变量可能为空时,这一点尤其重要,如本例所示; 如果没有引号,[命令就不会在那里接收任何参数.