Welcome to this Shell Scripting series! In this first part, we will learn about variables in a very simple and easy-to-understand way.
๐ Table of Contents
- What is a Variable?
- How to Create a Variable
- How to Use a Variable
- Variables That Cannot Change (readonly)
- Global and Local Variables
- Store Command Output in a Variable
- Simple Practical Example: System Info
- Simple Use Case: App Deployment Path
- Multi-Word Values (Use Quotes)
- Use Variables as Counters
- Check if a Variable is Empty
- Use Time in Variable (Backup File Name)
- Small Real-Life Script
- Quick Summary
- Practice for You
๐ What is a Variable?
A variable is like a small box where you store some information. Later, you can open the box and use that information again in your script.
✏️ How to Create a Variable
name="Pradeep"
course="Shell Scripting"
count=10
Important: There should be no space before or after the = sign.
❌ Wrong
name = "Pradeep"
✅ Correct
name="Pradeep"
๐ข How to Use a Variable
echo "Hello $name, welcome to $course training!"
Hello Pradeep, welcome to Shell Scripting training!
๐ง Variables That Cannot Change (readonly)
readonly company="MiddlewareBox"
If you try to change it again, the script will not allow it.
๐ Global and Local Variables
name="Pradeep" # Global variable
greet() {
local name="DevOps Engineer"
echo "Inside function: $name"
}
greet
echo "Outside function: $name"
Inside function: DevOps Engineer
Outside function: Pradeep
๐ง Store Command Output in a Variable
today=$(date)
echo "Today is: $today"
๐ป Simple Practical Example: System Info
host=$(hostname)
os=$(uname -s)
kernel=$(uname -r)
echo "Hostname: $host"
echo "OS: $os"
echo "Kernel: $kernel"
๐ Simple Use Case: App Deployment Path
app="orderservice"
version="v2.3"
path="/opt/apps/$app"
echo "Deploying $app version $version"
mkdir -p $path
cp $app-$version.jar $path/
๐งต Multi-Word Values (Use Quotes)
msg="Hello Shell Scripting Learners"
echo "$msg"
๐ Use Variables as Counters
count=1
while [ $count -le 3 ]; do
echo "Count: $count"
count=$((count+1))
done
❓ Check if a Variable is Empty
if [ -z "$name" ]; then
echo "Name is empty"
else
echo "Name is $name"
fi
⏱️ Use Time in Variable (Backup File Name)
time=$(date +%Y-%m-%d_%H-%M-%S)
file="backup_$time.tar.gz"
echo "Backup file name: $file"
๐งฐ Small Real-Life Script: Create User and Log
username="john"
log="/var/log/user_creation.log"
echo "Creating user: $username" | tee -a $log
useradd $username
echo "User $username created at $(date)" | tee -a $log
๐ Quick Summary
| Topic | Meaning |
|---|---|
| Variable | A box to store data |
| $variable | Use the value |
| readonly | Lock the value |
| local | Use only inside a function |
| $(command) | Save output of a command |
Next Part: Reading User Input in Shell Scripting
No comments:
Post a Comment