0
0
Bash Scriptingscripting~5 mins

User account management script in Bash Scripting

Choose your learning style9 modes available
Introduction

This script helps you add, delete, or list user accounts on a Linux system easily. It saves time and avoids mistakes when managing users.

When you need to create a new user quickly without typing many commands.
When you want to remove a user safely from the system.
When you want to see all current users on the system.
When managing multiple users and want a simple tool to automate tasks.
Syntax
Bash Scripting
#!/bin/bash

case "$1" in
  add)
    sudo useradd "$2"
    echo "User $2 added."
    ;;
  delete)
    sudo userdel "$2"
    echo "User $2 deleted."
    ;;
  list)
    cut -d: -f1 /etc/passwd
    ;;
  *)
    echo "Usage: $0 {add|delete|list} [username]"
    ;;
esac

The script uses case to handle different commands.

sudo is needed to run user management commands with proper permissions.

Examples
Adds a new user named alice.
Bash Scripting
./user_script.sh add alice
Deletes the user named bob.
Bash Scripting
./user_script.sh delete bob
Shows all users on the system.
Bash Scripting
./user_script.sh list
Sample Program

This script checks the first argument to decide what to do: add, delete, or list users. It also checks if the username is given when adding or deleting.

Bash Scripting
#!/bin/bash

case "$1" in
  add)
    if [ -z "$2" ]; then
      echo "Please provide a username to add."
      exit 1
    fi
    sudo useradd "$2" && echo "User $2 added."
    ;;
  delete)
    if [ -z "$2" ]; then
      echo "Please provide a username to delete."
      exit 1
    fi
    sudo userdel "$2" && echo "User $2 deleted."
    ;;
  list)
    cut -d: -f1 /etc/passwd
    ;;
  *)
    echo "Usage: $0 {add|delete|list} [username]"
    exit 1
    ;;
esac
OutputSuccess
Important Notes

Always run this script with proper permissions (usually with sudo) to manage users.

Be careful when deleting users to avoid losing important data.

You can extend this script to add passwords or other user settings.

Summary

This script automates adding, deleting, and listing users.

It uses simple commands and checks for required inputs.

Running with correct permissions is important for success.