2015年12月9日 星期三

[Linux 常見問題] Shell - How to calculate time difference in bash script?

Source From Here
Question
I print the start and end time using date +"%T", which results in something like:
10:33:56
10:36:10

How could I calculate and print the difference between these two? I would like to get something like:
2m 14s

How-To
I guess the easiest solution would be to obtain the time as the number of seconds since the Unix epoch, and then subtract them, doing the time arithmetic before displaying.

The -u parameter instructs date to return the time in UTC. This is needed in order to keep the timeline continuous : without that option, the calculation of diff could return an incorrect value if a DST transition happened between the two calls to date. This parameter is required by POSIX, so I bet it's widely supported across various Unices.
- test.sh
  1. #!/bin/sh  
  2. date1=$(date -u +"%s")  
  3. sleep 5  
  4. date2=$(date -u +"%s")  
  5. diff=$(($date2-$date1))  
  6. echo "$(($diff / 60)) minutes and $(($diff % 60)) seconds elapsed."  
Execution result:
# ./test.sh
0 minutes and 5 seconds elapsed.


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...