Menu

29 Oct 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

No comments:

Post a Comment