id
Overview
The id
command displays user and group IDs for the current user or specified user. It provides detailed identity information including real, effective, and supplementary group memberships.
Syntax
id [options] [user]
Common Options
Option | Description |
---|---|
-u |
Show only user ID |
-g |
Show only primary group ID |
-G |
Show all group IDs |
-n |
Show names instead of numbers |
-r |
Show real ID instead of effective |
-z |
Delimit entries with NUL |
Key Use Cases
- User identification
- Permission troubleshooting
- Security auditing
- Group membership verification
- Script access control
Examples with Explanations
Example 1: Basic Usage
id
Shows complete user and group information
Example 2: Specific User
id username
Shows information for specified user
Example 3: Numeric User ID
id -u
Returns only the numeric user ID
Example 4: Group Names
id -Gn
Shows all group names user belongs to
Understanding Output
Default output format:
uid=1000(user) gid=1000(user) groups=1000(user),4(adm),24(cdrom),27(sudo)
Components: - uid: User ID and name - gid: Primary group ID and name - groups: All group memberships
Common Usage Patterns
Root check:
[ "$(id -u)" -eq 0 ] && echo "Running as root"
Group membership check:
id -Gn | grep -q sudo && echo "User has sudo access"
User validation:
if id "$username" >/dev/null 2>&1; then echo "User exists" fi
Advanced Usage
Real vs effective ID:
id -ru # Real user ID id -u # Effective user ID
All group information:
id -G | tr ' ' '\n' | sort -n
Formatted output:
printf "User: %s (UID: %d)\n" "$(id -un)" "$(id -u)"
Performance Analysis
- Very fast operation
- No filesystem access needed
- Minimal system resources
- Good for frequent checks
- Efficient in scripts
Best Practices
- Use numeric IDs for reliable comparisons
- Check both user and group permissions
- Handle non-existent users gracefully
- Use appropriate options for specific needs
- Consider real vs effective IDs
Security Applications
Privilege escalation check:
if [ "$(id -u)" -ne "$(id -ru)" ]; then echo "Running with elevated privileges" fi
Group-based access:
if id -Gn | grep -q "admin"; then echo "Administrative access granted" fi
Scripting Examples
User directory creation:
USER_ID=$(id -u) USER_NAME=$(id -un) mkdir -p "/data/$USER_NAME" chown "$USER_ID" "/data/$USER_NAME"
Conditional execution:
if [ "$(id -u)" -eq 0 ]; then systemctl restart service else echo "Root privileges required" fi
Integration Examples
Logging with user info:
echo "$(date): User $(id -un) ($(id -u)) executed command" >> audit.log
Permission validation:
validate_user() { local required_group="$1" id -Gn | grep -q "$required_group" || { echo "Access denied: $required_group membership required" exit 1 } }
Troubleshooting
- User not found errors
- Permission denied issues
- Group membership problems
- Effective vs real ID confusion
- Numeric vs name resolution