Part 2: Bash Basics – Variables, Input/Output, and Exit Codes
Introduction
Now that you’ve written your first Bash script in Part 1, it’s time to dive deeper into the core building blocks of Bash scripting — variables, input/output operations, and exit codes.
These concepts are essential for writing dynamic and interactive scripts that can make decisions, store data, and handle user input.
Understanding Variables in Bash
Variables in Bash are like containers that store information — text, numbers, filenames, or command results.
🔹 Declaring a Variable
#!/bin/bash
name="Mishri"
echo "Hello, $name!"🟢 Output:
Hello, Mishri!💡 No spaces are allowed around the equal sign (
=).
❌name = "Mishri"→ This will cause an error.
🔹 Accessing Variables
Use a dollar sign ($) before the variable name to access its value:
echo $name🔹 Using Command Substitution
You can store the output of a command in a variable:
current_date=$(date)
echo "Today's date is: $current_date"🟢 Output Example:
Today's date is: Sun Nov 10 09:30:42 IST 2025
🔹 Environment Variables
These are system-wide variables available to all programs.
Example:
echo $HOME
echo $USERCommon environment variables:
| Variable | Description |
|---|---|
$HOME | User’s home directory |
$USER | Logged-in username |
$PWD | Current working directory |
$SHELL | Default shell |
$PATH | Directories Bash searches for executables |
🔹 Readonly Variables
Prevent accidental modification:
readonly app="MyScript"
app="NewScript" # ❌ This will throw an error
🔹 Unset a Variable
Remove a variable from memory:
unset name
echo $name # Output will be emptyReading User Input
You can make scripts interactive using the read command.
Example:
#!/bin/bash
echo "Enter your name:"
read username
echo "Welcome, $username!"🟢 Output:
Enter your name:
Mishri
Welcome, Mishri!Using read with Options
| Option | Description |
|---|---|
-p | Prompt message inline |
-s | Hide input (useful for passwords) |
-t | Timeout after specified seconds |
Example:
read -p "Enter your username: " user
read -s -p "Enter your password: " pass
echo
echo "Hello $user, login successful!"🧾 Output in Bash
🔹 Using echo
Prints text or variable values.
echo "Hello, World!"
echo "User: $USER"🔹 Using printf (More Controlled)
printf "Name: %s\nAge: %d\n" "Mishri" 25🟢 Output:
Name: Mishri
Age: 25✅
printfgives more formatting control thanecho.
🔁 Redirecting Output and Input
🔹 Output Redirection
| Symbol | Description | Example |
|---|---|---|
> | Write to file (overwrite) | echo "Hello" > file.txt |
>> | Append to file | echo "World" >> file.txt |
< | Read from file | cat < file.txt |
| ` | ` | Pipe output to another command |
Example:
echo "System Check: OK" > status.log
cat status.log🟢 Output:
System Check: OK⚠️ Exit Codes and Error Handling
Every Bash command returns an exit status (or exit code):
0= success ✅- Non-zero = error ❌
You can check the exit code of the last executed command using $?.
Example:
ls /tmp
echo $? # Should print 0 if success
ls /nonexistent_folder
echo $? # Will print non-zero (error)
🔹 Using Exit Codes in Scripts
#!/bin/bash
if ls /nonexistent_folder 2>/dev/null
then
echo "Directory found!"
else
echo "Error: Directory not found!"
exit 1
fi
Output:
Error: Directory not found!
🧩 Pro Tip: Always use meaningful exit codes in larger scripts (like
exit 1,exit 2) for debugging.
Combining Everything: Mini Script Example
Here’s a real example combining variables, input, and exit codes.
#!/bin/bash
# Simple Login Script
read -p "Enter username: " user
read -s -p "Enter password: " pass
echo
if [[ $user == "admin" && $pass == "1234" ]]; then
echo "Login successful. Welcome, $user!"
exit 0
else
echo "Invalid credentials. Access denied."
exit 1
fiOutput:
Enter username: admin
Enter password:
Login successful. Welcome, admin!Summary
In this section, you learned:
✅ How to define and use variables
✅ How to read user input interactively
✅ How to output data using echo and printf
✅ How to redirect input/output
✅ How to handle and interpret exit codes
🔜 Next in Series
👉 Part 3: Control Structures in Bash (if, for, while, case)
We’ll cover how to make your scripts smart — with conditions, loops, and branching.
