首页 > 解决方案 > 带有多个变量的 Bash if 语句

问题描述

您好,我正在尝试制作一个简单的 bash 脚本,并且对它很陌生。

使用 if 语句,我试图像时钟一样计数。

所以输出例如是 16:59:58, 16:59:59, 17:00:00

秒和分钟有效,但第一个 if 语句不起作用。

当它到达 23:59:59 时,它意味着去 00:00:00 但是它去到 24:60:00

有什么帮助吗?

if [[ "$hours" -eq 23 && "$minutes" -eq 60 && "$seconds" -eq 60 ]]
then
    seconds=0
    minutes=0
    hours=0
    ((date++))
else
    if [[ "$minutes" -eq 60 ]]
    then
        minutes=00
        ((hours++))
    else
        if [[ "$seconds" -eq 60 ]]
        then
            seconds=00
            ((minutes++))
        fi
    fi
fi

标签: bashif-statement

解决方案


从最低阶字段向上工作,而不是测试所有变量。

((seconds++))
if [[ $seconds -eq 60 ]]
then 
    seconds=0
    ((minutes++))
fi
if [[ $minutes -eq 60 ]]
then
    minutes=0
    ((hours++))
fi
if [[ $hours -eq 24 ]]
then
    hours=0
    ((date++))
fi

推荐阅读