Linux
Linux
🧾 1. Introduction
In Linux systems, users and groups are fundamental to managing access control,
permissions, and security. Shell scripting can automate user and group
management, making it efficient for system administrators to handle multiple tasks
at once.
🛠️ 2. Key Commands
Command Purpose
useradd Add a new user
userdel Delete a user
usermod Modify a user account
groupadd Add a new group
groupdel Delete a group
gpasswd -a Add user to group
gpasswd -d Remove user from group
passwd Set user password (manual or with input)
case $OPTION in
1)
read -p "Enter username to add: " USERNAME
useradd "$USERNAME"
echo " User '$USERNAME' added."
;;
2)
read -p "Enter username to delete: " USERNAME
userdel -r "$USERNAME"
echo " User '$USERNAME' deleted."
;;
3)
read -p "Enter group name to add: " GROUPNAME
groupadd "$GROUPNAME"
echo " Group '$GROUPNAME' added."
;;
4)
read -p "Enter group name to delete: " GROUPNAME
groupdel "$GROUPNAME"
echo " Group '$GROUPNAME' deleted."
;;
5)
read -p "Enter username: " USERNAME
read -p "Enter group name: " GROUPNAME
gpasswd -a "$USERNAME" "$GROUPNAME"
echo " User '$USERNAME' added to group '$GROUPNAME'."
;;
6)
read -p "Enter username: " USERNAME
read -p "Enter group name: " GROUPNAME
gpasswd -d "$USERNAME" "$GROUPNAME"
echo " User '$USERNAME' removed from group '$GROUPNAME'."
;;
*)
echo " Invalid option"
;;
esac
🔍 4. Explanation of the Script
• Uses useradd, userdel, groupadd, groupdel, gpasswd for user/group tasks.
• read gathers user input.
• case statement handles menu logic.
• Ensures script is run with root privileges ($EUID check).
• Uses -r flag with userdel to also delete the home directory.
USERNAME="student1"
GROUPNAME="students"
PASSWORD="Welcome@123"
✅ 6. Best Practices
• Always validate input to avoid accidental deletions.
• Use -m with useradd to create home directories.
• Store passwords securely and consider encrypting scripts.
• Log changes to a file for audit purposes.
🧠 7. Real-World Applications
Scenario Benefit of Scripting
School/college setup Add multiple student users and assign groups
Company onboarding Create users with passwords, assign roles
Cleanup scripts Automatically delete users who leave
Group permission setup Assign dev, test, admin access by group
🏁 8. Conclusion
Managing users and groups through shell scripts provides a powerful, efficient, and
repeatable way of administering Linux systems. Whether it’s creating a single user
or deploying hundreds, scripting reduces human error and ensures consistency.