程式扎記: [Linux 常見問題] Shell - How to calculate time difference in bash script?

標籤

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.


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!