• Home
  • WordPress
  • web Hosting
  • linux
  • mysql
  • nginx
  • apache2
  • devops

Raju Ginni

wordpress tutorials seo hosting etc

You are here: Home / Linux sysadmin tutorials linux system administrator / Shell Scripting Tutorial for Beginners ๐Ÿš€

Shell Scripting Tutorial for Beginners ๐Ÿš€

Shell scripting is a powerful way to automate tasks in Linux. This tutorial will cover the basics of shell scripting with examples.


Table of Contents

Toggle
    • 1. What is Shell Scripting?
      • Why Use Shell Scripting?
    • 2. Creating Your First Shell Script
      • Step 1: Create a Script File
      • Step 2: Add Shell Script Code
      • Step 3: Give Execute Permission
      • Step 4: Run the Script
    • 3. Variables in Shell Scripts
      • Defining and Using Variables
      • Using Command Substitution
    • 4. Taking User Input
    • 5. Conditional Statements
      • If Statement
    • 6. Loops in Shell Scripting
      • For Loop
      • While Loop
    • 7. Functions in Shell Scripts
    • 8. Working with Files
      • Check if a File Exists
      • Reading a File Line by Line
    • 9. Scheduling Scripts with Cron Jobs
    • 10. Shell Script Debugging
    • Conclusion
  • Advanced Shell Scripting Tutorial ๐Ÿš€
    • 1. Command-Line Arguments
      • Example: Using Arguments in a Script
    • 2. Using getopts for Argument Parsing
    • 3. Logging and Debugging
      • Log Script Output to a File
      • Enable Debugging Mode
    • 4. Handling Signals (trap)
    • 5. Parallel Processing with &
    • 6. Working with Arrays
    • 7. Processing Large Files Efficiently
      • Find and Replace in a File
      • Extract Specific Columns from a CSV
    • 8. Networking with Shell Scripts
      • Ping Multiple Servers
      • Download a File Using wget
    • 9. Automating Backups
    • 10. Scheduling Jobs with cron

1. What is Shell Scripting?

A shell script is a file containing a series of commands that the shell executes. It helps automate repetitive tasks, system administration, and process automation.

Why Use Shell Scripting?

โœ… Automate tasks
โœ… Reduce manual errors
โœ… Schedule jobs using cron
โœ… Process files efficiently


2. Creating Your First Shell Script

Step 1: Create a Script File

bash
nano myscript.sh

Step 2: Add Shell Script Code

bash
#!/bin/bash
echo "Hello, World!"
  • #!/bin/bash โ†’ Shebang (tells Linux to use the Bash shell)
  • echo โ†’ Prints text to the terminal

Step 3: Give Execute Permission

bash
chmod +x myscript.sh

Step 4: Run the Script

bash
./myscript.sh

Output:

Hello, World!

3. Variables in Shell Scripts

Defining and Using Variables

#!/bin/bash
name="Alice"
echo "Hello, $name!"

Output:

Hello, Alice!

Using Command Substitution

bash
date_today=$(date)
echo "Today's date is $date_today"

4. Taking User Input

bash
#!/bin/bash
echo "Enter your name:"
read user_name
echo "Hello, $user_name!"

Output:

yaml
Enter your name:
John
Hello, John!

5. Conditional Statements

If Statement

#!/bin/bash
echo "Enter a number:"
read num
if [ $num -gt 10 ]; then
echo โ€œNumber is greater than 10โ€
else
echo โ€œNumber is 10 or lessโ€
fi

6. Loops in Shell Scripting

For Loop

#!/bin/bash
for i in 1 2 3 4 5; do
echo "Number: $i"
done

While Loop

#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
((count++))
done

7. Functions in Shell Scripts

#!/bin/bash
function greet() {
echo "Hello, $1!"
}
greet Alice
greet Bob

Output:

Hello, Alice!
Hello, Bob!

8. Working with Files

Check if a File Exists

#!/bin/bash
file="myfile.txt"
if [ -f "$file" ]; then
echo "File exists"
else
echo "File does not exist"
fi

Reading a File Line by Line

#!/bin/bash
while read line; do
echo "Line: $line"
done < myfile.txt

9. Scheduling Scripts with Cron Jobs

To run a script automatically, use cron:

crontab -e

Add a line like:

0 9 * * * /home/user/myscript.sh

(Runs myscript.sh every day at 9 AM)


10. Shell Script Debugging

Run a script with debugging enabled:

bash
bash -x myscript.sh

Conclusion

You have learned the basics of shell scripting, including variables, loops, conditions, functions, and file handling. Shell scripting is widely used in automation, system administration, and DevOps.

Advanced Shell Scripting Tutorial ๐Ÿš€

Now that you know the basics, letโ€™s dive into more advanced concepts with practical examples.


1. Command-Line Arguments

Shell scripts can accept arguments from the command line.

Example: Using Arguments in a Script

#!/bin/bash
echo "Script Name: $0"
echo "First Argument: $1"
echo "Second Argument: $2"
echo "All Arguments: $@"
echo "Total Arguments: $#"

Usage:

./script.sh Alice Bob

Output:

yaml
Script Name: ./script.sh
First Argument: Alice
Second Argument: Bob
All Arguments: Alice Bob
Total Arguments: 2

2. Using getopts for Argument Parsing

To handle options like -f or -v:

bash
#!/bin/bash
while getopts "n:a:" opt; do
case $opt in
n) name="$OPTARG" ;;
a) age="$OPTARG" ;;
*) echo "Invalid option"; exit 1 ;;
esac
done
echo "Name: $name"
echo "Age: $age"

Usage:

./script.sh -n Alice -a 25

Output:

makefile
Name: Alice
Age: 25

3. Logging and Debugging

Log Script Output to a File

#!/bin/bash
exec > >(tee log.txt) 2>&1
echo "This is a log entry"

Enable Debugging Mode

#!/bin/bash
set -x # Enable debugging
echo "Debugging is ON"
set +x # Disable debugging

4. Handling Signals (trap)

trap allows capturing signals like CTRL+C (SIGINT).

#!/bin/bash
trap "echo 'CTRL+C detected! Exiting...'; exit" SIGINT

while true; do
echo โ€œRunningโ€ฆโ€
sleep 2
done

Press CTRL+C to see the trap message.


5. Parallel Processing with &

Run multiple tasks in parallel.

#!/bin/bash
echo "Task 1"; sleep 3 & # Runs in the background
echo "Task 2"; sleep 2 & # Runs in the background
wait # Wait for all background processes to finish
echo "All tasks completed"

6. Working with Arrays

#!/bin/bash
fruits=("Apple" "Banana" "Cherry")
echo "First fruit: ${fruits[0]}"
echo "All fruits: ${fruits[@]}"

7. Processing Large Files Efficiently

Instead of using cat file | awk, use:

awk '{print $1}' largefile.txt

Find and Replace in a File

sed -i 's/oldword/newword/g' file.txt

Extract Specific Columns from a CSV

cut -d ',' -f1,3 data.csv

8. Networking with Shell Scripts

Ping Multiple Servers

bash
#!/bin/bash
servers=("google.com" "github.com")

for server in โ€œ${servers[@]}โ€œ; do
ping -c 2 $server && echo โ€œ$server is reachableโ€ || echo โ€œ$server is downโ€
done

Download a File Using wget

bash
wget -O downloaded_file.zip "https://example.com/file.zip"

9. Automating Backups

bash
#!/bin/bash
backup_dir="/backup"
mkdir -p $backup_dir
tar -czf "$backup_dir/backup_$(date +%F).tar.gz" /home/user
echo "Backup completed!"

10. Scheduling Jobs with cron

Edit the crontab:

crontab -e

Run a script every day at midnight:

0 0 * * * /home/user/backup.sh

Linux sysadmin tutorials linux system administrator

  • top 10 apt & apt-get commands (most used) apt vs apt-get
  • If-Else Statements in Shell Scripting
  • linux commands pdf (files & Directories, zip & unzip process, search etc)
  • Find Files with Specific Text on Linux grep find command
  • linux performance tuning inode limit file descriptors tco, kernel etc
  • Variables and Data Types in Shell Scripting
  • Top 10 most used Cat commands with examples (create, view, append files)
  • Ip tables / ufw / firewall d commands for block port ip rate limiting
  • Top 10 zip / tar commands to compress & extract files in linux
  • TOP 10 mv & cp commands in linux to move & copy files in Linux
  • Top 10 GREP Commands in linux to search files directory words strings
  • lsof netstat commands to know listening ports in linux 3 ways
  • Upgrade Ubuntu from 18.04 (19.10) to 20.04 LTS command line or gui server | desktop
  • 3 Ways (SCP, rsync, Sftp) linux server migration between two remote server apache nginx
  • linux system specs commands (CPU, Memory, Disk )speed, type. manufacture
  • linux sysctl command tweaks & hardening
  • linux security limits.conf deciding user limits process limits for nginx server
  • ulimit linux unlimited command unlimto set & know user limits open files file descriptor max user process etc.
  • red hat linux certification cost jobs salary syllabus courses fees
  • ufw firewall commads allow port enable disable ubuntu 20.04
  • ddos attack prevention
  • change ssh port in linux - avoid sshd ddos attacks
  • ping command
  • memcached install ubuntu wordpress
  • check linux version (lsb_release -a) ubuntu debian 32 or 64 bit
  • rsync command linux with examples comparison to scp
  • how to uninstall package in linux ubuntu rpm, yum apt-get
  • increase open file limit linux File descriptor ft nginx , mysql, lemp
  • remove repository ubuntu
  • htop commad memory details virtual vs shard vs resident
  • chown command in Linux with Examples
  • Kill PHP process
  • VIrtual Memory vs RSS Memory vs Shared memory in Linux
  • oom killer fixing it by configuration linux ubuntu
  • Install Lemp nginx mysql php fpm Stack on Debian 11 with repository
  • connect two remote servers linux command line
  • auto start after oom killer Mysql & php fpm nginx etc ubuntu wth systemd or cron job
  • load average Linux 1, 5, 15 min 2,4,8 cores explained
  • Control Structures in Shell Scripting
  • Shell Scripting Roadmap for Beginners to Advanced
  • awk commands with practical examples
  • Shell Scripting Tutorial for Beginners ๐Ÿš€
  • find Command in Linux with Examples
  • sed Command in Linux with Examples (Beginner to Advanced)
  • Linux Text processing commands in with Examples
  • linux disk management commands
  • fdisk command in linux with examples
  • how to add a new disk in linux
  • Linux mount Command with Examples
  • fstab options with examples
  • Top 50 Shell Scripting Interview Questions and Answers
  • Linux Networking Interview Questions and Answers
  • Linux Networking Commands Cheat Sheet with Examples pdf
  • Netstat & SS Commands cheat sheet with examples Interview Questions
  • Nmap Cheat Sheet โ€“ Network Scanning & Security
  • Bash Brackets ([], (), {}, $( ), $(( ))) โ€“ Types, Uses & Examples

hi i am raju ginni, primalry i manage wordpress websites on GCP cloud platform as a cloud engineer, and create content on passionate things.
you can follow me on youtbe

ยฉ 2025 - All Rights Reserved Disclaimer & Privacy Policy