Menu

Tuesday, 28 October 2025

Linux Shell Scripting for Beginners – Part 1: What is a Variable?

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?

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

TopicMeaning
VariableA box to store data
$variableUse the value
readonlyLock the value
localUse only inside a function
$(command)Save output of a command



Next Part: Reading User Input in Shell Scripting

No comments:

Post a Comment