你可以使用date
命令來獲得當前的時間,進行定時之前和演藝工作後,計算這樣的區別:
#!/bin/bash
# Get time as a UNIX timestamp (seconds elapsed since Jan 1, 1970 0:00 UTC)
T="$(date +%s)"
# Do some work here
sleep 2
T="$(($(date +%s)-T))"
echo "Time in seconds: ${T}"
printf "Pretty format: %02d:%02d:%02d:%02d\n" "$((T/86400))" "$((T/3600%24))" "$((T/60%60))" "$((T%60))""
注: $((...))可用於基本的算術慶典 –注意:不要把空格前的負-,因爲這可能被解釋爲一個命令行選項。
參見:http://tldp.org/LDP/abs/html/arithexp.html
編輯:
此外,你可能想看看sed從由時間生成的輸出的搜索和提取子。
編輯:
實施例用於與毫秒定時(實際上納秒但截斷爲毫秒這裏)。您的date
版本必須支持%N
格式,bash
應支持大數字。
# UNIX timestamp concatenated with nanoseconds
T="$(date +%s%N)"
# Do some work here
sleep 2
# Time interval in nanoseconds
T="$(($(date +%s%N)-T))"
# Seconds
S="$((T/1000000000))"
# Milliseconds
M="$((T/1000000))"
echo "Time in nanoseconds: ${T}"
printf "Pretty format: %02d:%02d:%02d:%02d.%03d\n" "$((S/86400))" "$((S/3600%24))" "$((S/60%60))" "$((S%60))" "${M}"
免責聲明:
我原來的版本說
M="$((T%1000000000/1000000))"
但這被剪輯掉,因爲它顯然沒有對某些人的工作,而新版本的報道一樣。我不贊成這一點,因爲我認爲你只能使用剩下的部分,但是沒有得到批准。
選擇適合你的任何東西。
新[標籤:慶典]版本(> = 4.2)確實提供此一個'printf' syntaxe:'printf的-v時間戳「% (%s)T「-1」和「printf」%(%a%d%b%Y%T)T \ n「$ TimeStamp」的值可能是'-1':now,'-2':開始bash session'Integer':Unix timestamp – 2013-10-16 06:10:21
* ** *(在Linux下)** nanoseconds **,我寫了一個[函數](http://www.f-hauri。CH/VRAC/cours_truc-ET-astuces_2012-04-03/elap.bash)。你可以找到解釋[這裏](http://stackoverflow.com/a/14110859/1765658)。 – 2013-10-16 06:14:05