0
0
Bash Scriptingscripting~15 mins

Why error handling prevents silent failures in Bash Scripting - See It in Action

Choose your learning style9 modes available
Why error handling prevents silent failures
📖 Scenario: You are writing a small script to copy files and then delete the original files. You want to make sure the script tells you if something goes wrong, so you don't lose files silently.
🎯 Goal: Build a bash script that copies a file, checks if the copy succeeded, and only then deletes the original file. You will add error handling to prevent silent failures.
📋 What You'll Learn
Create a variable with the source file name
Create a variable with the destination file name
Copy the source file to the destination
Check if the copy command succeeded using $?
If the copy succeeded, delete the source file
If the copy failed, print an error message
Print a success message if the file was copied and deleted
💡 Why This Matters
🌍 Real World
Scripts that copy or move files must confirm success to avoid losing data silently. Error handling helps catch problems early.
💼 Career
System administrators and DevOps engineers write scripts that automate file management. Knowing error handling prevents costly mistakes.
Progress0 / 4 steps
1
Set up source and destination file variables
Create a variable called source_file and set it to example.txt. Create another variable called dest_file and set it to backup.txt.
Bash Scripting
Need a hint?

Use = to assign values to variables without spaces around it.

2
Copy the source file to the destination
Write a command to copy the file from $source_file to $dest_file using the cp command.
Bash Scripting
Need a hint?

Use cp "$source_file" "$dest_file" to copy files safely with quotes.

3
Add error handling to check if copy succeeded
Use an if statement to check if the last command succeeded by testing $? equals 0. If yes, delete the $source_file using rm. Otherwise, print Error: Copy failed.
Bash Scripting
Need a hint?

Use if [ $? -eq 0 ] to check success, then rm to delete, else echo to print error.

4
Print success message after deleting source file
Inside the if block where you delete $source_file, add a command to print File copied and original deleted successfully.
Bash Scripting
Need a hint?

Use echo to print the success message inside the if block.