Reputation: 193
I'm trying to write a shell script using the date and who commands to print how the number of hours and minutes a user has been logged in. I can assume it is less than 24 hours. How would I do this?
I would think I would somehow extract the time from the date command and from the who command and somehow subtract them, but I'm not sure how I would implement that.
Upvotes: 1
Views: 1572
Reputation: 185284
#!/bin/bash
export LANG=C
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 "%s %s\n" "$((diff_seconds_between_date_and_now/3600)) hours" \
"$((diff_seconds_between_date_and_now%3600/60)) minutes"
I takes the oldest line whith the specified user :
Usage :
$ bash script.bash <USERNAME>
Sample output :
$ bash script.bash sputnick
528 hours 6 minutes
Upvotes: 4