Advanced Bash Scripting: User Input, File Handling & Error Logging

Introduction

Once you’ve mastered the basics of Bash, it’s time to go deeper. In this blog, we’ll explore user input, file handling, and error logging—features that make Bash scripts powerful and production-ready. These are essential skills for any DevOps engineer automating real-world server tasks.


🧑‍💻 1. Reading User Input

Let’s prompt the user for input at runtime:

#!/bin/bash

echo "Enter your name:"
read name
echo "Welcome, $name!"
  • read captures input from the user.
  • Great for interactive scripts.

📁 2. File Handling in Bash

Check if a file exists:

file="/etc/passwd"

if [ -f "$file" ]; then
echo "$file exists."
else
echo "$file not found."
fi

📝 Read a file line-by-line:

filename="list.txt"

while read -r line; do
echo "Processing: $line"
done < "$filename"

Useful when:

  • Reading hostnames for SSH
  • Parsing config files
  • Reading usernames or backup lists

🚨 3. Error Logging

Redirect standard output and error:

#!/bin/bash

logfile="backup.log"
errfile="error.log"

echo "Starting backup..." > "$logfile"

cp /source/folder /backup/folder 2> "$errfile"

if [ $? -ne 0 ]; then
echo "Backup failed. Check $errfile"
else
echo "Backup completed successfully." >> "$logfile"
fi

🔍 Explanation:

  • 2> redirects stderr (errors)
  • > redirects stdout (output)
  • $? checks exit status

🧪 Bonus: User Confirmation Before Deleting Files

read -p "Do you really want to delete /tmp/files? (y/n): " confirm

if [[ $confirm == "y" ]]; then
rm -rf /tmp/files
echo "Files deleted."
else
echo "Operation canceled."
fi

🧰 Real-World DevOps Use Case

Imagine a nightly EC2 cleanup script:

#!/bin/bash

instances=$(aws ec2 describe-instances --filters "Name=tag:Temp,Values=true" --query "Reservations[].Instances[].InstanceId" --output text)

log="ec2_cleanup.log"

for id in $instances; do
echo "Terminating $id" >> $log
aws ec2 terminate-instances --instance-ids $id 2>> $log
done

echo "Cleanup complete."

Now that’s Bash scripting with impact!


🔗 Internal Links:


✅ Conclusion

Bash scripting is the heart of DevOps automation. By learning user interaction, file parsing, and error handling, you’re writing scripts that are not just smart—but safe and scalable.

Leave a Comment

Your email address will not be published. Required fields are marked *