Shell scripting is a powerful way to automate tasks in Linux. This tutorial will cover the basics of shell scripting with examples.
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
Step 2: Add Shell Script Code
#!/bin/bash
β Shebang (tells Linux to use the Bash shell)echo
β Prints text to the terminal
Step 3: Give Execute Permission
Step 4: Run the Script
Output:
3. Variables in Shell Scripts
Defining and Using Variables
Output:
Using Command Substitution
4. Taking User Input
Output:
5. Conditional Statements
If Statement
6. Loops in Shell Scripting
For Loop
While Loop
7. Functions in Shell Scripts
Output:
8. Working with Files
Check if a File Exists
Reading a File Line by Line
9. Scheduling Scripts with Cron Jobs
To run a script automatically, use cron
:
Add a line like:
(Runs myscript.sh
every day at 9 AM)
10. Shell Script Debugging
Run a script with debugging enabled:
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
Usage:
Output:
2. Using getopts
for Argument Parsing
To handle options like -f
or -v
:
Usage:
Output:
3. Logging and Debugging
Log Script Output to a File
Enable Debugging Mode
4. Handling Signals (trap
)
trap
allows capturing signals like CTRL+C
(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.
6. Working with Arrays
7. Processing Large Files Efficiently
Instead of using cat file | awk
, use:
Find and Replace in a File
Extract Specific Columns from a CSV
8. Networking with Shell Scripts
Ping Multiple Servers
for server in “${servers[@]}“; do
ping -c 2 $server && echo “$server is reachable” || echo “$server is down”
done
Download a File Using wget
9. Automating Backups
10. Scheduling Jobs with cron
Edit the crontab:
Run a script every day at midnight: