Mastering Bash Scripting: Variables, Loops, and Conditionals
Bash scripting is the backbone of Linux automation. For developers, especially those coming from a Java background, Bash serves as a powerful tool to automate repetitive tasks, manage deployments, and handle system administration. While Java is a compiled, strongly-typed language, Bash is an interpreted scripting language designed for shell interaction. Understanding how to handle variables, control flow with loops, and make decisions with conditionals is essential for any Linux professional.
Understanding Variables in Bash
In Bash, variables are used to store data that can be referenced later. Unlike Java, Bash is loosely typed, meaning you do not need to declare a data type like int or String. However, Bash is very sensitive to syntax, particularly regarding spaces.
Variable Declaration and Usage
To assign a value, use the = operator without spaces. To access the value, prefix the variable name with a $ sign.
# Correct way
APP_NAME="InventoryManager"
VERSION=1.2
# Accessing variables
echo "Starting $APP_NAME version $VERSION"
Java vs. Bash: Variable Comparison
In Java, you are used to strict declarations. Here is how the logic compares:
// Java Variable Declaration
String appName = "InventoryManager";
double version = 1.2;
System.out.println("Starting " + appName + " version " + version);
Conditionals: Making Decisions
Conditionals allow your script to perform different actions based on specific criteria. Bash uses the if [ condition ]; then ... fi syntax. Note that the square brackets [ ] are actually a command called test, so spaces around them are mandatory.
Common Comparison Operators
- -eq: Equal to (integer)
- -ne: Not equal to (integer)
- -z: String is empty
- -f: File exists and is a regular file
- -d: Directory exists
Example of an if-else statement checking if a directory exists before running a Java application:
DEPLOY_DIR="/opt/java_app"
if [ -d "$DEPLOY_DIR" ]; then
echo "Deployment directory exists. Proceeding..."
else
echo "Error: Directory not found. Creating it now."
mkdir -p "$DEPLOY_DIR"
fi
Loops: Automating Repetitive Tasks
Loops are used to iterate over a list of items, such as files in a directory or numbers in a range. The most common loops are for and while.
The For Loop
A for loop is ideal when you know the number of iterations or have a specific list of items.
# Iterating through a list of service names
for SERVICE in "database" "cache" "api"
do
echo "Restarting $SERVICE..."
done
The While Loop
A while loop continues as long as a condition remains true. This is often used for monitoring processes.
COUNT=1
while [ $COUNT -le 5 ]
do
echo "Retry attempt: $COUNT"
((COUNT++))
done
Java Comparison: The For Loop
The logic remains the same as a standard Java loop, but the syntax is more lightweight in Bash:
// Java equivalent of the for loop
String[] services = {"database", "cache", "api"};
for (String service : services) {
System.out.println("Restarting " + service + "...");
}
Real-World Use Case: Automated Log Cleanup
System administrators often write scripts to manage log files. Below is a practical script that checks if a log file exists and deletes it if it exceeds a certain size.
LOG_FILE="/var/log/app.log"
MAX_SIZE=1024 # Size in KB
if [ -f "$LOG_FILE" ]; then
FILE_SIZE=$(du -k "$LOG_FILE" | cut -f1)
if [ "$FILE_SIZE" -gt "$MAX_SIZE" ]; then
echo "Log too large ($FILE_SIZE KB). Archiving..."
mv "$LOG_FILE" "$LOG_FILE.old"
touch "$LOG_FILE"
fi
fi
Common Mistakes to Avoid
- Spaces in Assignment: Writing
VAR = "value"will fail. It must beVAR="value". - Missing Quotes: Always wrap variables in double quotes (e.g.,
"$VAR") to prevent issues with spaces in file names. - Shebang Missing: Forgetting
#!/bin/bashat the top of the file may cause the script to run in a different shell (like sh), leading to syntax errors. - Integer vs. String Comparison: Using
==for numbers instead of-eqcan lead to unexpected behavior in some Bash versions.
Interview Notes: Bash Scripting Essentials
- What is the Shebang? It is the first line (
#!) that tells the OS which interpreter to use to execute the script. - How do you check the exit status of the last command? Use the variable
$?. A value of 0 means success, while anything else indicates an error. - What is the difference between [ ] and [[ ]]?
[[ ]]is an extended test command that is more powerful, supporting pattern matching and logical operators like&&and||without escaping. - How do you make a script executable? Use the command
chmod +x script_name.sh.
Summary
Bash scripting is a fundamental skill for automating Linux environments. By mastering variables, you can store dynamic data; with conditionals, you can build logic into your automation; and with loops, you can handle bulk operations efficiently. While the syntax differs from Java, the underlying logic of programming remains the same. Practice by writing small scripts to automate your daily dev-ops tasks, and you will soon find Bash to be an indispensable part of your toolkit.