Loops & Conditions – Making Scripts Think Like a Ninja!
A true ninja 🥷 is unpredictable, strategic, and adaptable – just like your scripts should be! With if statements, loops, and case conditions, your shell scripts will think, decide, and repeat like a true cyber warrior! ⚔️
If Statements – The Ninja’s Decision-Making
A ninja chooses their path wisely. In scripting, we use if
statements to make decisions.
Example: Checking if the user is a true ninja!
#!/bin/bash
echo "Enter your ninja rank (master/apprentice):"
read rank
if [ "$rank" == "master" ]; then
echo "🥷 Welcome, Master Ninja! The shadows bow before you!"
elif [ "$rank" == "apprentice" ]; then
echo "👶 Keep training, young warrior! Your time will come!"
else
echo "❌ Unknown rank. Are you even a ninja?!"
fi
💡 The if
statement is like a ninja choosing whether to strike or stay hidden. 🎭
Loops – Repeating Tasks Like a True Warrior
Ninjas train every day. Your scripts should too! Loops let you repeat tasks automatically.
Example: Training a ninja 5 times using a for loop
#!/bin/bash
for i in {1..5}; do
echo "🥷 Ninja training day $i: Practice your stealth!"
done
🌀 Types of Loops in Shell Scripting:
Loop Type | Purpose |
---|---|
for | Repeats a task a set number of times |
while | Repeats as long as a condition is true |
until | Repeats until a condition becomes true |
Case Statements – Choosing the Right Path
A wise ninja doesn’t always follow one path. The case
statement is like a decision tree for your scripts. 🌳
Example: Choosing a ninja weapon
#!/bin/bash
echo "Choose your weapon (katana/shuriken/nunchucks):"
read weapon
case $weapon in
katana)
echo "⚔️ A fine choice! The katana is a weapon of precision."
;;
shuriken)
echo "🎯 Ah! The art of ranged combat."
;;
nunchucks)
echo "🔥 Bruce Lee would be proud!"
;;
*)
echo "❌ That’s not a ninja weapon!"
;;
esac
💡 case
statements make your script more readable and elegant – like a ninja’s movements! 🏯
Ninja Training Challenge
✅ Modify the ninja rank script to give a custom greeting for 'Sensei'
✅ Create a loop that asks for a secret password and exits only when it’s correct
✅ Make a case statement that responds to different Linux commands entered by the user