« »
2008-02-03Shell

296

Linux Shell Script: 時間計算

  • 現在時間 + 22:09:53 = 何時?
  • 現在時間 + 128 分鐘 = 何時?

#!/bin/bash

# User Defined Variables
# H,M,S  系統時間
# rhflag 0 = 當日, 1 = 明天, 2 = 後天…
# strUsage 參數提示訊息
# timeoffset 使用者輸入的時間 (時:分:秒)
# oh,om,os 從 timeoffset 提列出來的 時, 分, 秒 (case 1) / 進位值 (case 2)
# rh,rm,rs 運算結果 時, 分, 秒
# offset 使用 -h, -m, -s 參數時, 使用者帶入的數值

# System Variables
# $# 參數數量
# $0 Shell Script 檔名
# $1 第一個參數
# $2 第二個參數

H=`date +%H`
M=`date +%M`
S=`date +%S`
rhflag=0
strUsage=”Usage:\n$0 hh:mm:ss\nor\n$0 [-h|-m|-s] number\n”

case “$#” in
1)
 timeoffset=$1
 oh=`echo $timeoffset | awk -F ‘:’ ‘{print $1}’`
 om=`echo $timeoffset | awk -F ‘:’ ‘{print $2}’`
 os=`echo $timeoffset | awk -F ‘:’ ‘{print $3}’`
 rs=`expr $S + $os`
 if [ $rs -gt 59 ]; then
  ((rs -= 60))
  om=`expr $om + 1`
 fi
 rm=`expr $M + $om`
 if [ $rm -gt 59 ]; then
  ((rm -= 60))
  oh=`expr $oh + 1`
 fi
 rh=`expr $H + $oh`
 if [ $rh -gt 24 ]; then
  ((rhflag = rh / 24))
  ((rh %= 24))
 fi
;;

2)
 offset=$2
 if [ $1 == "-h" ]; then
  rh=`expr $H + $offset`
  rm=$M
  rs=$S
  if [ $rh -gt 24 ]; then
   ((rhflag = rh / 24))
   ((rh %= 24))
  fi
 elif [ $1 == "-m" ]; then
  rh=$H
  rm=`expr $M + $offset`
  rs=$S
  if [ $rm -gt 59 ]; then
   ((oh = rm / 60))
   ((rm %= 60))
   rh=`expr $H + $oh`
   if [ $rh -gt 24 ]; then
    ((rhflag = rh / 24))
    ((rh %= 24))
   fi
  fi
 elif [ $1 == "-s" ]; then
  rh=$H
  rm=$M
  rs=`expr $S + $offset`
  if [ $rs -gt 59 ]; then
   ((om = rs / 60))
   ((rs %= 60))
   ((rm += om))
   if [ $rm -gt 59 ]; then
    ((oh = rm / 60))
    ((rm %= 60))
    ((rh += oh))
    if [ $rh -gt 24 ]; then
     ((rhflag = rh / 24))
     ((rh %= 24))
    fi
   fi
   
  fi
 else
  printf $strUsage
  exit 1
 fi
;;

*)
 printf $strUsage
 exit 1
;;
esac

if [ $rh -eq 24 ]; then
 rh=0
 rhflag=1
fi
echo “$H:$M:$S”
echo “$rhflag $rh:$rm:$rs”

 執行範例

timeadd 22:09:53

14:52:10 (目前時間)
1 13:2:3 (明天下午一點零二分零三秒)

timeadd -m 128

14:53:52 (目前時間)
0 17:1:52 (今天下午五點零一分五十二秒)

自問自答

Q: 為什麼要做這個無聊的 Shell Script?
A: 因為我想知道商人這一趟過去什麼時候會到呀~ XD
A:
A: (Travian 遊戲畫面截圖)

相關網頁

您还可能感兴趣的内容

日志信息 »

该日志于2008-02-03 06:27由 x72 发表在Shell分类下, 通告目前不可用,你可以至底部留下评论。

没有评论

发表评论 »


返回顶部