Skip to main content

Renaming Users and Updating Metadata

Rename User (with home directory update)

# 1. Rename the user account
usermod -l new_username old_username

# 2. Rename the group (if using the same name)
groupmod -n new_groupname old_groupname

# 3. Rename and move the home directory
usermod -d /home/new_username -m new_username

# 4. Verify changes
id new_username
ls -la /home/new_username

Complete User Rename Script

For renaming cocodeploy to coco-deploy:

#!/bin/bash
set -euo pipefail

# Script: rename_user.sh
# Usage: ./rename_user.sh <old_username> <new_username>
# Example: ./rename_user.sh cocodeploy coco-deploy

OLD_USER="${1:?Error: Old username required}"
NEW_USER="${2:?Error: New username required}"

# Validate user exists
if ! id "$OLD_USER" >/dev/null 2>&1; then
echo "Error: User $OLD_USER does not exist"
exit 1
fi

echo "Renaming user: $OLD_USER$NEW_USER"

# Get current home directory
HOME_DIR=$(grep "^$OLD_USER:" /etc/passwd | cut -d: -f6)
NEW_HOME_DIR="/home/$NEW_USER"

echo "Home directory: $HOME_DIR$NEW_HOME_DIR"

# Kill any active processes for this user
if pgrep -u "$OLD_USER" > /dev/null; then
echo "Killing processes for $OLD_USER..."
pkill -9 -u "$OLD_USER" || true
fi

# Rename the user
echo "Renaming user account..."
usermod -l "$NEW_USER" "$OLD_USER"

# Rename the group
echo "Renaming group..."
groupmod -n "$NEW_USER" "$OLD_USER"

# Rename and move home directory
echo "Moving home directory..."
usermod -d "$NEW_HOME_DIR" -m "$NEW_USER"

# Update file ownership recursively
echo "Updating file ownership..."
find "$NEW_HOME_DIR" -exec chown "$NEW_USER:$NEW_USER" {} + 2>/dev/null || true

# Verify the change
echo ""
echo "✔ Rename complete!"
echo "User details:"
id "$NEW_USER"
echo "Home directory:"
ls -ld "$NEW_HOME_DIR"

Usage:

chmod +x rename_user.sh
./rename_user.sh cocodeploy coco-deploy

Updating User GECOS Information (Metadata)

GECOS fields store metadata like full name, room number, phone, etc.

Format: Full Name,Room,Work Phone,Home Phone,Other

Update via chfn (interactive)

sudo chfn coco-deploy

Update via chfn (individual fields)

# Full name
sudo chfn -f "Coco Deploy Service" coco-deploy

# Room number
sudo chfn -r "Server Room A" coco-deploy

# Work phone
sudo chfn -w "+1-555-0001" coco-deploy

# Home phone
sudo chfn -h "+1-555-0002" coco-deploy

Update via usermod (all at once)

sudo usermod -c "Coco Deploy Service,Server Room A,+1-555-0001,+1-555-0002,Production" coco-deploy

View Current GECOS Information

# To use finger you may need to install it
apt update
apt install finger -y

# Method 1: finger command
finger coco-deploy

# Method 2: grep /etc/passwd
grep "^coco-deploy:" /etc/passwd | cut -d: -f5

# Method 3: full details
id coco-deploy
getent passwd coco-deploy