whoami
Overview
The whoami
command prints the effective username of the current user. It’s a simple but essential command for user identification in scripts and system administration.
Syntax
whoami
Key Use Cases
- User identification in scripts
- Security verification
- System administration
- Access control checks
- Logging and auditing
Examples with Explanations
Example 1: Basic Usage
whoami
Returns the current username
Example 2: Script Usage
if [ "$(whoami)" != "root" ]; then
echo "This script must be run as root"
exit 1
fi
Common Usage Patterns
Root check:
[ "$(whoami)" = "root" ] && echo "Running as root"
User-specific paths:
USER=$(whoami) CONFIG_DIR="/home/$USER/.config"
Logging:
echo "$(date): $(whoami) executed script" >> audit.log
Best Practices
- Use in security-sensitive scripts
- Combine with conditional statements
- Consider using
id -u
for numeric UID - Use for user-specific configurations
- Include in audit trails
Integration Examples
Backup script:
BACKUP_DIR="/backups/$(whoami)" mkdir -p "$BACKUP_DIR"
Temporary files:
TEMP_FILE="/tmp/$(whoami)_$$_temp"
Permission check:
if [ "$(whoami)" != "admin" ]; then echo "Access denied" exit 1 fi
Security Considerations
- Shows effective user, not real user
- Can be different in sudo context
- Use
logname
for original login name - Consider
id
for more detailed info