Linux Shell Scripting (Day 05): Advanced Linux Shell Scripting for DevOps Engineers with User Management ๐Ÿš€

Aditya SharmaAditya Sharma
2 min read

Welcome to Day 05 of Linux Shell Scripting for DevOps Engineers!
This section covers advanced scripting concepts with real-world examples that are essential in the DevOps world. Scripts are written in a simple and easy-to-understand way.

What You'll Learn Today :-

  • How to use loops (for, while).

  • Writing .sh (shell) scripts properly.

  • Using if/else conditions.

  • Creating users with shell scripts.

๐Ÿ” for Loop in Shell :-

Used when you know how many times you want to run a command.

for i in 1 2 3 4 5
do
  echo "Welcome $i times"
done

โžก๏ธ Output:

Welcome 1 times
Welcome 2 times
...
...
Welcome 5 times

๐Ÿ”„ while Loop :-

Used when the number of iterations is unknown, runs while a condition is true.

count=1
while [ $count -le 5 ]
do
  echo "Count is $count"
  ((count++))
done

โœ… if/else Statement :-

Used to make decisions in scripts.

num=10
if [ $num -gt 5 ]; then
  echo "Number is greater than 5"
else
  echo "Number is 5 or less"
fi

๐Ÿ“‚ Writing a .sh File :-

  1. Create a script file:

     vim hello.sh
    
  2. Add the shebang line at the top:

     #!/bin/bash
     echo "Hello from script!"
    
  3. Make it executable:

     chmod +x hello .sh
    
  1. Run the Script :

     ./hello.sh
    

๐Ÿ‘ค Create a New User with Shell Script

A basic user-creation script (needs root access):

#!/bin/bash

read -p "Enter username to create: " username
sudo useradd $username

if [ $? -eq 0 ]; then
  echo "User $username created successfully โœ…"
else
  echo "Failed to create user โŒ"
fi
0
Subscribe to my newsletter

Read articles from Aditya Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aditya Sharma
Aditya Sharma

DevOps Enthusiast | Python | Chef | Docker | GitHub | Linux | Shell Scripting | CI/CD & Cloud Learner | AWS