简体   繁体   中英

Bash script to return hours and minutes user has been logged

I would like my script to return the number of hours and minutes the user has been logged on to the server for the past 7 days. I have written the script below. But it keeps returning 0 hours, 0 minutes. Any help on where to modify so as to achieve my goal would be appreciated.

#!/bin/sh

export LANG=C
grep "$(date +"%Y-%m-%d")" /var/log/syslog
awk -v d1="$(date --date="-5 min" "+%b %_d %H:%M")" -v d2="$(date "+%b %_d %H:%M")" '$0 > d1 && $0 < d2 || $0 ~ d2' /var/log/syslog
date_string=$(
who |
sort -k3M -k4n |
awk '{if ($1 ~ user) {print $3, $4, $5;exit}}' user="$1"
)
diff_seconds_between_date_and_now=$(
(
    $(date +%s) - $(date -d "$date_string" +%s)
)
)
printf "Last $(id -u)"
printf " Since "
printf "%s %s\n" "$((diff_seconds_between_date_and_now/604800)) day(s)"
printf "   "
printf "%s %s\n" "$((diff_seconds_between_date_and_now/3600)) hours" "$((diff_seconds_between_date_and_now%3600/60)) minutes"

考虑使用“last”命令:

last -s '-7 days' username

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM