
In our previous blog, we covered the basics of shell scripting. In this post, we will dive into some essential topics: variables, conditions (string, numeric, file, and logical), arrays, and conditional statements.
These concepts are widely used in real-world DevOps tasks. Whenever you write a shell script, conditions and variables are essential for automating decisions and handling dynamic data.
Variables in Shell Scripting
Variables store values that can be reused throughout a script, making your scripts more flexible and easier to maintain.
Global Variables
Global variables are accessible anywhere in the script after declaration.
name="Linux" echo "Welcome to $name" echo "Learning $name shell scripting"
Output:
Welcome to Linux Learning Linux shell scripting
Local Variables
Local variables exist only inside a block, usually a function.
my_function() {
local city="Hyderabad"
echo "Inside function: $city"
}
my_function
echo "Outside function: $city"Output:
Inside function: Hyderabad # No output for the second echo because the variable is local to the function.
String Conditions
String conditions are used to compare text values.
=→ equals!=→ not equal-z→ string is empty-n→ string is not empty
Examples
name="Linux" if [ "$name" = "Linux" ]; then echo "Platform is Linux" fi file_name="" if [ -z "$file_name" ]; then echo "Filename is empty" fi
Output:
Platform is Linux Filename is empty
Numeric Conditions
Numeric conditions compare integer values:
-eq→ equal-ne→ not equal-gt→ greater than-lt→ less than-ge→ greater than or equal-le→ less than or equal
Examples
num1=10 num2=20 if [ $num1 -lt $num2 ]; then echo "$num1 is less than $num2" fi if [ $num1 -ne $num2 ]; then echo "$num1 is not equal to $num2" fi
Output:
10 is less than 20 10 is not equal to 20
File Conditions
File conditions check file existence, type, and permissions:
-e→ file exists-f→ regular file-d→ directory-r→ readable-w→ writable-x→ executable-s→ not empty-L→ symbolic link
Examples
file="/etc/passwd" if [ -e "$file" ]; then echo "$file exists" fi if [ -r "$file" ]; then echo "$file is readable" fi dir="/tmp" if [ -d "$dir" ]; then echo "$dir is a directory" fi
Output:
/etc/passwd exists /etc/passwd is readable /tmp is a directory
Logical Conditions
Logical operators help create complex conditions:
&&→ AND, executes when all conditions are true||→ OR, executes when at least one condition is true!→ NOT, reverses the condition
Examples
num1=10 num2=20 if [ $num1 -lt $num2 ] && [ $num1 -eq 10 ]; then echo "Both conditions are true" fi if [ $num1 -eq 5 ] || [ $num2 -eq 20 ]; then echo "At least one condition is true" fi if ! [ $num1 -eq 5 ]; then echo "num1 is not equal to 5" fi
Output:
Both conditions are true At least one condition is true num1 is not equal to 5
Arrays in Shell Scripting
Arrays store multiple values in a single variable. Indexing starts at 0.
array[@]→ prints all elements#array[@]→ length of arrayarray[0]→ first elementarray[-1]→ last elementarray+=(value)→ add elementunset array[index]→ remove specific elementunset array→ remove entire array
Examples
servers=("web01" "db01" "cache01")
echo "All servers: ${servers[@]}"
echo "Total servers: ${#servers[@]}"
echo "First server: ${servers[0]}"
servers+=("proxy01")
unset servers[1] # removes db01
echo "Updated servers: ${servers[@]}"Output:
All servers: web01 db01 cache01 Total servers: 3 First server: web01 Updated servers: web01 cache01 proxy01
Conditional Statements
Conditional statements control the flow of execution in scripts based on specific conditions.
if Statement
Commands execute only when the condition is true.
status=$(systemctl is-active nginx) if [ "$status" = "active" ]; then echo "Nginx service is running" fi
if-else Statement
Executes one block if true, another if false.
if [ -f "/tmp/testfile" ]; then echo "File exists" else echo "File does not exist" fi
if-elif-else Statement
Handles multiple conditions.
cpu_load=$(uptime | awk -F 'load average:' '{ print $2 }' | cut -d, -f1)
if (( $(echo "$cpu_load < 1.0" | bc -l) )); then echo "CPU load is low" elif (( $(echo "$cpu_load >= 1.0 && $cpu_load < 2.0" | bc -l) )); then
echo "CPU load is medium"
else
echo "CPU load is high"
ficase Statement
Matches a variable against multiple patterns. Cleaner for multiple values.
service="nginx" case $service in "nginx") echo "Web server selected";; "mysql") echo "Database server selected";; "redis") echo "Cache server selected";; *) echo "Unknown service";; esac
Real-World Examples (DevOps)
1. Check if a service is running
services=("nginx" "mysql" "docker")
for svc in "${services[@]}"; do
if systemctl is-active --quiet $svc; then
echo "$svc is running"
else
echo "$svc is not running"
fi
done2. Check disk usage
disk_usage=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')
if [ $disk_usage -gt 80 ]; then
echo "Warning: Disk usage is above 80%"
else
echo "Disk usage is normal"
fi3. Validate file before backup
backup_file="/tmp/data.tar.gz" if [ -e "$backup_file" ] && [ -s "$backup_file" ]; then echo "Backup file exists and is not empty" else echo "Backup file missing or empty" fi
Leave a Reply