Shell scripting helps automate repetitive tasks using command-line instructions. This section covers a beginner-friendly project to create directories and user accounts using a shell script on an Ubuntu server.
mkdir shell-scripting
cd shell-scriptingvim my_first_shell_script.shPaste this code into the file:
#!/bin/bash
# Create directories
mkdir Folder1
mkdir Folder2
mkdir Folder3
# Create users
sudo useradd user1
sudo useradd user2
sudo useradd user3ls -latrUse ls -l to view permissions:
ls -l my_first_shell_script.shExpected output: -rw-r--r-- (No execute permission)
./my_first_shell_script.shYou should see:
bash: ./my_first_shell_script.sh: Permission denied
chmod +x my_first_shell_script.sh
./my_first_shell_script.shlsExpected: Folder1 Folder2 Folder3
id user1
id user2
id user3To make scripts robust and avoid errors when folders or users already exist, we use checks like:
[ ! -d "$dir" ] && mkdir "$dir" # Only create if folder doesn't exist
id "$user" &>/dev/null || useradd "$user" # Only add user if not foundThis prevents crashes and makes your scripts reusable and reliable.
| Problem | Cause | Solution |
|---|---|---|
Permission denied when running script |
File isn’t marked executable | Run: chmod +x my_first_shell_script.sh |
command not found: vim |
Vim editor isn’t installed | Run: sudo apt install vim |
useradd: user already exists |
You’ve already created the user | Run: sudo deluser user1 before re-running script |
mkdir: cannot create directory |
Folder already exists | Use rm -r Folder1 before running the script again |
| No output or visible effect | Commands are being silently executed | Add echo statements to print progress, or use set -x to debug |
At the top of your script:
#!/bin/bashThis line tells the system to use the Bash shell to run your script. It’s called a shebang.
- Defines the Interpreter: Ensures the correct shell (e.g., bash, sh, zsh) is used.
- Enables Portability: Scripts run consistently across different systems.
- Avoids Confusion: Without it, the system might not execute the script as expected.
Alternative example:
#!/bin/sh # for POSIX-compliant shellTo trace and debug script execution:
#!/bin/bash
set -x # Enable debugging
# Commands here...- Logs each command before execution.
- Helps trace failures or logic bugs.
You can disable debugging mid-script with:
set +xname="John"echo $nameOutput:
John
Variables store data like strings or numbers. echo is used to display them.
This hands-on scripting task demonstrated how to automate folder and user creation, manage permissions, and use variables in Bash. Shell scripting is essential for every DevOps engineer—helping you automate, replicate, and scale tasks efficiently.






