在 Bash 中减去日期格式

在 Bash 中减去日期格式

我正在尝试创建一个倒计时 - 很可能是困难的方式。我的设置如下:

#! /bin/bash 

#When to execute command 
execute=$(date +"%T" -d "22:30:00")

#Current time
time=$(date +"%T")

#Subtract one from the other.... the below is line 11
math=$(("$execute"-"$time"))

#Repeat until time is 22:30:00
until [ "$math" == "00:00:00" ]; do  

echo "Countdown is stopping in $math"
sleep 1
clear 
done

问题是……它不起作用。这是终端中的输出:

   /path/to/file/test.sh: line 11: 22:30:00-16:39:22: syntax error in expression (error token is “:30:00-16:39:22”) 
    Countdown is stopping in 

首先,错误信息,什么问题?

其次,“倒计时即将停止”信息应该包含倒计时停止的小时、分钟和秒。为什么没有呢?请记住,我不是专业人士。

答案1

问题在于声明

math=$(("$execute"-"$time"))

因为executetime包含格式为的值%H:%M:%S。但是 bash 的算术扩展无法评估时间格式。

除了%H:%M:%S格式化之外,您还可以将时间转换为秒,进行算术运算,然后以所需的格式打印。

就像是

#!/bin/bash

#When to execute command
execute=$(date +"%s" -d "22:30:00")

time=$(date +"%s")
math=$((execute-time))

if [[ $math -le 0 ]]; then
    echo "Target time is past already."
    exit 0
fi

#Repeat until time is 22:30:00
while [[ $math -gt 0 ]]; do
    printf "Countdown is stopping in %02d:%02d:%02d" $((math/3600)) $(((math/60)%60)) $((math%60))
    sleep 1
    clear

    # Reset count down using current time;
    # An alternative is to decrease 'math' value but that
    # may be less precise as it doesn't take the loop execution time into account
    time=$(date +"%s")
    math=$((execute-time))
done

答案2

谢谢@PP 的回答。您的方法一开始有效,但重启后就失效了……此外,它并没有停止循环 - 这意味着它变成了负数,之后再也没有执行过命令。这是我最终做的:

#! /bin/bash

#When to execute command
execute=$(date +"%s" -d "22:30:00")

time=$(date +"%s")
math=$((execute-time))

#Repeat until time is 22:30:00
until [ "$time" == "$execute" ]; do
    printf "The server will stop in %02d:%02d:%02d" $((math/3600)) $(((math/60)%60)) $((math%60))
    sleep 1
    clear

    # Reset count down using current time;
    # An alternative is to decrease 'math' value but that
    # may be less precise as it doesn't take the loop execution into account
    time=$(date +"%s")
    math=$((execute-time))

if [ "$time" == "$execute" ]; then

break
fi 

done 

echo "Cycle has ended"

相关内容