The script was exiting silently on the GROUPS=$(groups ... | cut ...) line — set -eo pipefail caused bash to terminate the script before any echo output, making it appear to do nothing. Replace set -euo pipefail with set -u and explicit error handling. Admin scripts must always report what happened, never exit silently. Also: use id -nG instead of groups|cut pipe, add verification step after userdel, and log each operation for visibility.
88 lines
2.3 KiB
Bash
Executable file
88 lines
2.3 KiB
Bash
Executable file
#!/bin/bash
|
|
# Remove user (analyst or admin)
|
|
# Usage: sudo remove-analyst username [--force]
|
|
#
|
|
# Note: This script uses explicit error handling instead of set -e.
|
|
# set -e causes silent exits with command substitutions and pipefail,
|
|
# which is unacceptable for admin scripts that must always report what happened.
|
|
|
|
set -u # Catch unset variables, but no -e (explicit error handling)
|
|
|
|
if [[ $EUID -ne 0 ]]; then
|
|
echo "Error: This script must be run as root (use sudo)"
|
|
exit 1
|
|
fi
|
|
|
|
# Parse arguments
|
|
FORCE=false
|
|
USERNAME=""
|
|
|
|
for arg in "$@"; do
|
|
case $arg in
|
|
--force|-f)
|
|
FORCE=true
|
|
;;
|
|
*)
|
|
USERNAME="$arg"
|
|
;;
|
|
esac
|
|
done
|
|
|
|
if [[ -z "$USERNAME" ]]; then
|
|
echo "Usage: sudo remove-analyst username [--force]"
|
|
echo " --force, -f Skip confirmation prompt"
|
|
exit 1
|
|
fi
|
|
|
|
# Check if user exists
|
|
if ! id "$USERNAME" &>/dev/null; then
|
|
echo "Error: User '$USERNAME' does not exist"
|
|
exit 1
|
|
fi
|
|
|
|
# Prevent removing yourself
|
|
CURRENT_USER=$(logname 2>/dev/null || echo "${SUDO_USER:-unknown}")
|
|
if [[ "$USERNAME" == "$CURRENT_USER" ]]; then
|
|
echo "Error: Cannot remove yourself"
|
|
exit 1
|
|
fi
|
|
|
|
# Get user groups for info (safe extraction, no pipefail issues)
|
|
GROUPS=$(id -nG "$USERNAME" 2>/dev/null) || GROUPS="(unknown)"
|
|
|
|
echo "Removing user: $USERNAME"
|
|
echo " Groups: $GROUPS"
|
|
echo " Home: /home/$USERNAME"
|
|
|
|
if [[ "$FORCE" != true ]]; then
|
|
read -p "Are you sure? [y/N] " -n 1 -r
|
|
echo ""
|
|
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
|
|
echo "Cancelled"
|
|
exit 0
|
|
fi
|
|
fi
|
|
|
|
# Remove user and home directory
|
|
echo " Deleting OS user..."
|
|
if userdel -r "$USERNAME" 2>/dev/null; then
|
|
echo " User and home directory removed"
|
|
elif userdel "$USERNAME" 2>/dev/null; then
|
|
echo " User removed (userdel -r failed, cleaning up home manually)"
|
|
if [[ -d "/home/$USERNAME" ]]; then
|
|
rm -rf "/home/$USERNAME"
|
|
echo " Home directory /home/$USERNAME removed"
|
|
fi
|
|
else
|
|
echo "Error: Failed to remove user '$USERNAME'"
|
|
echo " Check if processes are running as this user: ps -u $USERNAME"
|
|
exit 1
|
|
fi
|
|
|
|
# Verify removal
|
|
if id "$USERNAME" &>/dev/null; then
|
|
echo "Warning: User '$USERNAME' still exists (OS login system may have re-created it)"
|
|
exit 1
|
|
fi
|
|
|
|
echo "User '$USERNAME' removed successfully"
|