Variables & Arguments – Storing Secrets Like a Ninja!
Ah, young cyber warrior! 🥷 It is time to unlock the power of variables – the scrolls of wisdom that hold information inside your scripts. You will also learn arguments, the secret messages passed between commands. Master this, and you'll control the command line like a true ninja! ⚔️
The Secret of Variables
A variable is like a hidden scroll 🏯 that stores information for later use.
How to create a variable?
#!/bin/bash
# Declare a secret variable
ninja_name="Shadow Blade"
# Use the secret
echo "Welcome, $ninja_name! 🥷"
💡 Notice the $
before the variable name when using it! Forget $
and your script won’t recognize the variable (just like a ninja without a mask 🏴☠️).
The Power of Arguments – Passing Secret Messages
Arguments allow you to send secret data to a script. 🤫
Example: Passing a name when running a script
#!/bin/bash
echo "Welcome, $1! 🥷"
echo "You have been chosen for a secret mission!"
How to run it?
./my_noob_script.sh Hattori
🛡 Output:
Welcome, Hattori! 🥷
You have been chosen for a secret mission!
Special Argument Variables
Symbol | Meaning |
---|---|
$1, $2, $3 | Arguments passed to the script |
$0 | The script name itself |
$# | Number of arguments given |
$@ | All arguments as a list |
$? | Exit status of the last command |
💡 Think of arguments as scrolls delivered to your script by secret ninja messengers. 🏯📜
Interactive Scripts – Talking to the Ninja
Instead of passing arguments, you can ask for input during script execution.
Example: Taking user input
#!/bin/bash
echo "Enter your ninja name: "
read ninja_name
echo "Ah, welcome $ninja_name! Your training begins now! 🥷⚔️"
💡 The read
command is like a wise old master waiting for your response. Answer wisely! 😎
Secret Mission – Test Your Knowledge
Try modifying your script to:
✅ Ask the user for their favorite Linux command
✅ Print out how many arguments were passed to the script
✅ Create a random password generator using $RANDOM