Bash Script to Check User Login History Easily
last username inside a script to check a user's login history; for example, last $1 where $1 is the username passed as an argument.Examples
How to Think About It
last command to retrieve login records for that user. The output shows when and from where the user logged in, making it easy to track login activity.Algorithm
Code
#!/bin/bash if [ -z "$1" ]; then echo "Usage: $0 username" exit 1 fi last "$1"
Dry Run
Let's trace the script with input 'root' through the code
Check if username is provided
Input argument is 'root', so proceed.
Run last command
Execute 'last root' to get login history.
Display output
Print the login records for user 'root'.
| Step | Action | Value |
|---|---|---|
| 1 | Input username | root |
| 2 | Command run | last root |
| 3 | Output | root pts/0 192.168.1.10 Fri Apr 26 10:00 still logged in |
Why This Works
Step 1: Input validation
The script checks if a username is given using -z "$1" to avoid running without input.
Step 2: Using last command
The last command reads login records from system logs to show user login history.
Step 3: Output display
The script prints the login history directly, making it easy to see when and where the user logged in.
Alternative Approaches
#!/bin/bash if [ -z "$1" ]; then echo "Usage: $0 username" exit 1 fi lastlog -u "$1"
#!/usr/bin/env python3 import sys import subprocess if len(sys.argv) < 2: print(f"Usage: {sys.argv[0]} username") sys.exit(1) user = sys.argv[1] result = subprocess.run(['last', user], capture_output=True, text=True) print(result.stdout)
Complexity: O(n) time, O(n) space
Time Complexity
The last command reads through the login records file which grows with the number of logins, so time is proportional to the number of entries.
Space Complexity
The script uses minimal extra memory, just enough to hold the command output, so space is proportional to the output size.
Which Approach is Fastest?
Using lastlog is faster but less detailed; the main last command provides full history but takes longer on large logs.
| Approach | Time | Space | Best For |
|---|---|---|---|
| last command | O(n) | O(n) | Full detailed login history |
| lastlog command | O(1) | O(1) | Quick last login time |
| Python wrapper | O(n) | O(n) | Extensible scripting with login history |