[Date] Shell Scripting
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
What is Shell Scripting?
Shell scripting is writing a series of Linux/Unix commands in a file and executing them to
automate tasks.
Automates: Backups, software installs, user creation, monitoring, deployments
Shell Types: bash, sh, zsh, ksh
Hello World & Basics
#!/bin/bash
echo "Hello, World!"
• #!/bin/bash: Shebang — tells the system to use Bash shell
• echo: Prints output
Run:
chmod +x script.sh
./script.sh
Variables
name="Prakash"
echo "Welcome $name"
• No space around =
• Use $ to access
Input & Output
read -p "Enter your name: " username
echo "Hello, $username"
• read: Reads user input
• -p: Prompts during read
Conditional Statements
if Statement
3
if [ "$age" -ge 18 ]; then
echo "Adult"
fi
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
echo "Hello $1"
}
greet "Prakash"
• $1: First argument to function
Exit Status
• $?: Last command exit status
• 0: Success, non-zero: Failure
ls file.txt
echo "Status: $?"
Command Line Arguments
#!/bin/bash
echo "Script: $0"
echo "First Arg: $1"
echo "All Args: $@"
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
String & File Manipulations
String
str="DevOps"
echo "Length: ${#str}"
echo "Sub: ${str:0:3}"
File Read
while read line; do
echo "$line"
done < filename.txt
File Test Operators
if [ -f file.txt ]; then echo "File exists"; fi
if [ -d folder ]; then echo "Directory exists"; fi
Operator Test
-f Regular file
-d Directory
-s Not empty
-e Exists
-r Read permission
Error Handling
command || echo "Command failed"
command && echo "Command succeeded"
Cron Jobs
Edit cron:
crontab -e
Cron syntax:
# ┌──────── min (0 - 59)
# │ ┌────── hour (0 - 23)
# │ │ ┌──── day (1 - 31)
# │ │ │ ┌── month (1 - 12)
# │ │ │ │ ┌─ weekday (0 - 6; Sunday = 0)
# │ │ │ │ │
# * * * * * command
6
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"
Create Users in Bulk
#!/bin/bash
for user in user1 user2 user3; do
useradd $user
echo "$user:Password123" | chpasswd
done
Advanced Topics
set -e, set -x
set -e # Exit on error
set -x # Debug mode
trap (Cleanup on Exit)
trap "echo 'Script interrupted'" SIGINT
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
Shell Scripting Interview Questions
1. Difference between " and ' in Bash?
2. How to debug a shell script?
3. What is the use of $?, $0, $1, $@, $#?
4. How do you handle errors in a script?
5. Write a script to find if a number is even or odd.
6. What is the difference between [ and [[ in Bash?
7. Explain the role of trap, exec, and source.
8. How do you use cron to schedule jobs?
9. Difference between .bashrc and .bash_profile?
10. How to monitor a log file in real-time with a script?