2016-03-30 33 views
-1

我有我的bash腳本這兩個funtions如何在bash中正確設置時間?

function start_time { 
    unset date1 
    date1=$(date +"%s") 
} 

function stop_time { 
    unset date2 diff minutes seconds hours varhours varminutes varseconds 
    date2=$(date +"%s") 
    diff=$(($date2-$date1)) # <-- There is seconds 
    minutes=$((($diff/60))) 
    seconds=$((($diff % 60))) 
    hours=$((($minutes/60))) 

    if [ $hours != 0 ]; then varhours=$(echo "$hours Hours"); fi 
    if [ $minutes != 0 ]; then varminutes=$(echo "$minutes Minutes"); fi 
    if [ $seconds != 0 ]; then varseconds=$(echo "$seconds Seconds"); fi 

    echo "++ $1 : $varhours $varminutes $varseconds " 
} 

所以我在下面的方式執行它們;

start_time  
"some bash job for example sleep command for a while" 
stop_time "execution time was" 

如果腳本採用例如,3小時23分鐘50秒,它示出了通過以下方式輸出

執行時間爲:4小時203分鐘50秒

所以,我的問題是,是否有某種方式顯示正確的分鐘數,我的意思是123分鐘是腳本執行某項工作所花的總時間,所以預期的輸出結果必須是:3小時23分鐘50秒。

+0

它看起來像你的時間四捨五入有,它應該是2小時3分鐘。由於123分鐘比2小時多一點。 –

+0

您是否需要顯示小時數,或者只是簡單地使用分鐘和秒鐘? – bluerojo

+0

http://stackoverflow.com/questions/8903239/how-to-calculate-time-difference-in-bash-script < - 顯示如何計算腳本中的時間差異 – bluerojo

回答

1

爲什麼重新發明車輪?該time命令就已經做你想要什麼:

command time --format "execution time was :%E" sleep 100 

(這是使用的command time代替time,以確保你是不是調用一些shell內置)

+2

'哪個不是標準化的,可能不存在並且找不到它(相對而言(很貴)。爲了這個確切目的,shell提供了一個內置的'command'。 –