Created
September 22, 2025 20:27
-
-
Save iammarxg/9ffa8c5b0d2980439e66b566cc01dd00 to your computer and use it in GitHub Desktop.
A script for creating and adding a user to a group in Ubuntu
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # Prompt the user to enter the user name. | |
| # Create a new user using useradd . | |
| set_username() { | |
| read -p "Enter username: " username | |
| if id "$username" &>/dev/null; then | |
| echo "User '$username' already exists. Please try a different name." | |
| set_username | |
| else sudo useradd $username | |
| fi | |
| } | |
| # Prompt the user to enter a strong password (8 characters or more) and set it using passwd. | |
| set_password() { | |
| while true; do | |
| read -s -p "Enter a strong password (8 characters or more): " password | |
| echo | |
| if [[ ${#password} -ge 8 ]]; then | |
| echo "$username:$password" | sudo chpasswd | |
| if [[ $? -eq 0 ]]; then | |
| echo "Password set successfully." | |
| break | |
| else | |
| echo "Failed to set password. Try again." | |
| fi | |
| else | |
| echo "Password must be at least 8 characters. Try again." | |
| fi | |
| done | |
| } | |
| # Prompt the user to enter a default group name. | |
| # Append the entered group name to the user groups using usermod -aG <groupname> <username>. | |
| adduser_to_group() { | |
| while true; do | |
| read -p "Enter a default group name: " groupname | |
| sudo usermod -aG "$groupname" "$username" 2>/dev/null | |
| if [[ $? -eq 0 ]]; then | |
| echo "User '$username' added to group '$groupname'." | |
| break | |
| else | |
| echo "Failed to add user to group '$groupname'. Try again." | |
| fi | |
| done | |
| } | |
| # At the end, the script should ask the user to confirm creating the new user with a message. If the user decided not to create the user, delete it using userdel -r <user_name>. | |
| confirm_creation() { | |
| read -p "Confirm creating user '$username'? (y/n): " confirm | |
| if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then | |
| sudo userdel -r "$username" | |
| echo "User '$username' has been deleted." | |
| else | |
| echo "User '$username' successfully created." | |
| fi | |
| } | |
| set_username | |
| set_password | |
| adduser_to_group | |
| confirm_creation |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment