在bash中,如何减去日期格式

分享于 

3分钟阅读

ubuntu

  繁體

问题:

我试图写一个倒计时 - 我已经写成这样:


#! /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的arithmetic扩展无法理解时间的格式。

替代%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:


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





for  form  格式  scripts  日期  BASH  
相关文章