This script provides system administrators with a clear overview of the system’s current uptime and detailed last login information for human user accounts (UID ≥ 500). It displays key details such as the terminal, login date, login time, and session status for each account.
Click to view script…
#!/bin/bash
# Title: Detailed macOS User Last Login Checker with System Uptime
# Description:
# This script lists human user accounts (UID ≥ 500) on macOS and displays detailed information about their last login session.
# It also shows the current system uptime at the top.
#
# The output includes:
# - System Uptime: How long the machine has been running since the last boot.
# - Username : The account name.
# - Terminal : The terminal device used during login.
# - Login Date : The date of the login (Day Month Date).
# - Login Time : The time when the login occurred.
# - Login Status : Indicates if the session is still active or has ended.
#
# Note: "Never logged in" is shown if no login record exists.
#
# Retrieve and display system uptime
systemUptime=$(uptime)
echo "System Uptime: $systemUptime"
echo ""
# Print header for the login details
echo "Username | Terminal | Login Date | Login Time | Login Status"
echo "---------------------------------------------------------------------"
# List users with their UniqueIDs and process each one.
dscl . -list /Users UniqueID | while read username uid; do
if [ "$uid" -ge 500 ]; then
# Retrieve the most recent login record for the user
loginInfo=$(last -1 "$username" | head -n 1)
# Check if there is a valid login record
if echo "$loginInfo" | grep -q "wtmp begins"; then
echo "$username | - | - | - | Never logged in"
else
# Parse the login record:
# Field 1: Username (redundant here)
# Field 2: Terminal (e.g., ttys000)
# Fields 3-5: Login Date (e.g., "Mon Feb 17")
# Field 6: Login Time (e.g., "05:44")
# Fields 7+: Login Status (e.g., "still logged in" or the session end time)
terminal=$(echo "$loginInfo" | awk '{print $2}')
login_date=$(echo "$loginInfo" | awk '{print $3, $4, $5}')
login_time=$(echo "$loginInfo" | awk '{print $6}')
login_status=$(echo "$loginInfo" | cut -d' ' -f7-)
# Output the parsed details in a table-like format
printf "%-8s | %-8s | %-16s | %-10s | %s\n" "$username" "$terminal" "$login_date" "$login_time" "$login_status"
fi
fi
done
# Legend:
# System Uptime - How long the system has been running since the last boot.
# Username - The account name.
# Terminal - The terminal device used during login.
# Login Date - The date of the login (Day Month Date).
# Login Time - The time of the login.
# Login Status - The current status of the login session.