- 论坛徽章:
- 0
|
题目要求:
用date和who命令编写一个名为conntime的程序,显示一个用户已经登陆到系统的小时数和分钟数(假定不超过24小时).
(由于这道题目所在及以前章节都未涉及到awk的知识,所以最好不要使用awk.)
下面的是我写的,有没有更简便的方法?
- #!/bin/bash
- if [ -z "$(who | sed -n "/^$1 /p")" ]
- then
- echo the name not found
- exit 1
- fi
- D=$(date | cut -c10-11)
- M=$(date | cut -c13-14)
- W=$(who | sed -n "/$1/p" | cut -c30-31)
- w=$(who | sed -n "/$1/p" | cut -c33-34)
- if [ "$D" -eq "$W" -a "$M" -eq "$w" ]
- then
- echo 24:00
- elif [ "$D" -eq "$W" -a "$M" -gt "$w" ]
- then
- echo 'invalid time'
- elif [ "$D" -eq "$W" -a "$M" -lt "$w" ]
- then
- ( expr $D + 24 - $W - 1 && expr $M + 60 - $w ) | paste -s -d:
- elif [ "$D" -lt "$W" -a "$M" -eq "$w" ]
- then
- ( expr $D + 24 - $W && echo 00 ) | paste -s -d:
- elif [ "$D" -lt "$W" -a "$M" -gt "$w" ]
- then
- ( expr $D + 24 - $W && expr $M - $w ) | paste -s -d:
- elif [ "$D" -lt "$W" -a "$M" -lt "$w" ]
- then
- ( expr $D + 24 - $W - 1 && expr $M + 60 - $w ) | paste -s -d:
- elif [ "$D" -gt "$W" -a "$M" -eq "$w" ]
- then
- ( expr $D - $W && echo 00 ) | paste -s -d:
- elif [ "$D" -gt "$W" -a "$M" -gt "$w" ]
- then
- ( expr $D - $W && expr $M - $w ) | paste -s -d:
- elif [ "$D" -gt "$W" -a "$M" -lt "$w" ]
- then
- ( expr $D - $W - 1 && expr $M + 60 - $w ) | paste -s -d:
- fi
复制代码 |
|