Shell Scripting Guide
Shell Scripting Guide
Guide
(Beginner to Advanced)
Prakash Reddy
1
Table of Contents
1. What is Shell Scripting?
2. Hello World & Basics
3. Variables
4. Input & Output (read, echo)
5. Conditional Statements (if, if-else, case)
6. Loops (for, while, until)
7. Functions
8. Exit Status & Return Values
9. Command Line Arguments
10. Arrays
11. String & File Manipulations
12. File Test Operators
13. Error Handling
14. Cron Jobs
15. Practical Examples
16. Advanced Topics
17. Best Practices
18. Interview Questions
2
Run:
chmod +x script.sh
./script.sh
Variables
name="Prakash"
echo "Welcome $name"
• No space around =
• Use $ to access
Conditional Statements
if Statement
3
if-else
if [ "$age" -ge 18 ]; then
echo "Adult"
else
echo "Minor"
fi
elif
if [ "$score" -gt 90 ]; then
echo "Excellent"
elif [ "$score" -gt 50 ]; then
echo "Pass"
else
echo "Fail"
fi
case Statement
read -p "Enter choice: " ch
case $ch in
1) echo "Start" ;;
2) echo "Stop" ;;
*) echo "Invalid" ;;
esac
Loops
for Loop
for i in 1 2 3; do
echo "Number: $i"
done
while Loop
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
((count++))
done
Functions
greet() {
4
Exit Status
• $?: Last command exit status
• 0: Success, non-zero: Failure
ls file.txt
echo "Status: $?"
Special variables
• $1, $2, $3
• All variables passed: $@
• number of variables: $#
• script name: $0
• present working directory: $PWD
• home directory of current user: $HOME
• which user is running this script: $USER
• process id of current script: $$
• process id of last command in background: $!
Arrays
fruits=("Apple" "Banana" "Cherry")
echo "First: ${fruits[0]}"
echo "All: ${fruits[@]}"
5
File Read
while read line; do
echo "$line"
done < filename.txt
Error Handling
command || echo "Command failed"
command && echo "Command succeeded"
Cron Jobs
Edit cron:
crontab -e
Cron syntax:
Example:
0 1 * * * /home/user/backup.sh
Practical Examples
Backup Script
#!/bin/bash
src="/var/www/html"
dest="/backup/html_$(date +%F).tar.gz"
tar -czf $dest $src
echo "Backup saved at $dest"
Advanced Topics
set -e, set -x
Logging
exec > >(tee -i log.txt)
exec 2>&1
7
Best Practices
Practice Why It Matters
Use #!/bin/bash Defines shell explicitly
Use set -euo pipefail Makes script fail-safe
Use quotes around variables Avoids word splitting & globbing
Handle errors Prevents silent failures
Use functions Improves reusability
Use logging Easier debugging & audit