使用BASH的秒表脚本

时间:2017-08-10 15:22:52

标签: bash date stopwatch

此脚本启动秒表并获取1个整数参数。秒表将在指定的时间开始,以秒为单位(如果给出了args),或者从' 0'(如果没有给出args)开始。但是,如果我将参数传递给此脚本,则会妨碍脚本的核心功能,即几天不再更新。

if [ $1 ]
then
    date1=(`date +%s`+$1);
else
    date1=`date +%s`;
fi


while ! read -t0; do 
    days=$(( $(($(date +%s) - date1)) / 86400 ))
    echo -ne "$days day(s) and $(date -u --date @$((`date +%s` - $date1)) +%H:%M:%S)\r";
    sleep 0.1
done

让脚本从特定时间开始非常重要。我无法做到这一点。否则,脚本可以正常工作而不传递任何参数

谢谢。

2 个答案:

答案 0 :(得分:1)

我会像这样写你的剧本,但我承认我不理解你遇到的实际问题。请在您的问题中添加更多详细信息。

#!/bin/bash
start=$(date +%s)
if [[ $1 == ?([+-])+([0-9]) ]]; then
    ((start += $1))
elif [[ $1 ]]; then
    echo "invalid argument '$1': ignoring it"
fi

while true; do
    now=$(date +%s)
    days=$(( (now - start) / 86400 ))
    seconds=$(( (now - start) % 86400 ))
    printf "\r%d day(s) and %s " $days $(date --utc --date @$seconds +%T)
    sleep 0.1
done

答案 1 :(得分:0)

这是最后的工作脚本。感谢格伦杰克曼。

# this script initiates a stopwatch
# this script can take 1 integer argument
# the stopwatch will start at the specified time, in seconds( if args are given ), or from '0'( if no args are given )
# Example : if you want the timer to start at 4 days, 5 hours, 33 minutes and 9 seconds, then you'd run the Script as :
# ./Stopwatch $((86400*4 + 3600*5 + 60*33 + 9 ))

if [ $1 ]
then
    date1=$(($(date +%s) - $1));
else
    date1=`date +%s`;
fi


while ! read -t0; do 
    days=$(( $(($(date +%s) - date1)) / 86400 ))
    echo -ne "$days day(s) and $(date -u --date @$((`date +%s` - $date1)) +%H:%M:%S)\r";
    sleep 0.1
done