Skip to main content

Creating Users

System User

System users are typically for services that don't require login access.

adduser --system --group --home /opt/name name

Normal User with Locked Password

Creates a user with a specific UID/GID, useful for consistent deployments across systems.

useradd -u 2000 -g 2000 -d "/opt/deploy" -m -s /usr/sbin/nologin deploy

User Creation Script with Parameters

This script accepts input parameters for flexibility across different deployments:

#!/bin/bash
set -euo pipefail

# Script: create_user.sh
# Usage: ./create_user.sh <username> <uid> <gid> <home_dir> <shell> [gecos]
# Example: ./create_user.sh cortex 2001 2001 /opt/cortex /bin/bash "Cortex Bot"

validate_input() {
if [[ $# -lt 5 ]]; then
echo "Usage: $0 <username> <uid> <gid> <home_dir> <shell> [gecos]"
echo "Example: $0 cortex 2001 2001 /opt/cortex /bin/bash 'Cortex Bot'"
exit 1
fi

# Validate UID is numeric and doesn't exist
if ! [[ $2 =~ ^[0-9]+$ ]]; then
echo "Error: UID must be numeric"
exit 1
fi

if id -u "$2" >/dev/null 2>&1; then
echo "Error: UID $2 already exists"
exit 1
fi

# Validate GID is numeric
if ! [[ $3 =~ ^[0-9]+$ ]]; then
echo "Error: GID must be numeric"
exit 1
fi
}

create_user() {
local username=$1
local uid=$2
local gid=$3
local home_dir=$4
local shell=$5
local gecos="${6:-System Account}"

echo "Creating group: $username (GID: $gid)"
groupadd -g "$gid" "$username" 2>/dev/null || echo "Group already exists"

echo "Creating user: $username (UID: $uid)"
useradd \
-u "$uid" \
-g "$username" \
-d "$home_dir" \
-m \
-s "$shell" \
-c "$gecos" \
"$username"

echo "Locking password for $username"
passwd -l "$username" &> /dev/null

echo "✔ User $username created successfully"
echo " UID: $uid, GID: $gid"
echo " Home: $home_dir"
echo " Shell: $shell"
}

validate_input "$@"
create_user "$@"

Usage:

chmod +x create_user.sh
./create_user.sh cortex 2001 2001 /opt/cortex /bin/bash "Cortex Bot"
./create_user.sh coco-deploy 2002 2002 /opt/coco-deploy /bin/bash "Coco Deploy Bot"