我正在编写一个shell脚本来跟踪启动&一些正在运行的程序的结束时间。我需要这个脚本来打印可读的开始&结束时间和最终以秒为单位的时间成本。
为了计算成本,我写了这样的
START=$(date +%s)
# ................
END=$(date +%s)
DIFF=$(( $END - $START ))
echo "Start Time: $START" >> $LOGFILE 2>&1
echo "End Time: $END" >> $LOGFILE 2>&1
echo "Running time: $DIFF seconds" >> $LOGFILE 2>&1
这适用于计算,但$START和$END只能打印为秒数。
如果我像下面的一样定义它们,它可以打印可读的日期格式
START=$(date +%c)
END=$(date +%c)
然而,DIFF=$(($END-$START))不再适用于它们。
因此,我想知道shell脚本中是否有任何解决方案,这样我既可以以定义的格式打印日期,也可以用它们进行一些计算。
顺便说一句,我使用的是AIX。
如果你有GNU日期,你可以使用epoch时间
date -d @$START +%c
否则,执行
read start start_display < <(date +"%s %c")
# ...
read end end_display < <(date +"%s %c")
diff=$(( $end - $start ))
echo "Start time: $start_display"
如果你没有使用能够处理替代的外壳,
set -- $(date +"%s %c")
start=$1; shift
start_display=$*
如果您使用bash,请利用内置的$SECONDS变量,对于新的bash进程,该变量从零开始,并每秒递增。
start_display=$(date)
# ...
echo "Start Time: $start_display"
echo "End Time: $(date)"
echo "Running time: $SECONDS seconds"
您可以使用date-d@Seconds将秒转换为日期。例如:
$ date +%s
1377095983
$ date -d @1377095983
Wed Aug 21 20:09:43 IST 2013