📖 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
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
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
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
Hint
Use echo to print the success message inside the if block.
Practice
(1/5)
1. Why is error handling important in bash scripts?
easy
A. It automatically fixes errors without user input
B. It makes scripts run faster
C. It shows when something goes wrong instead of failing silently
D. It reduces the size of the script
Solution
Step 1: Understand silent failures
Silent failures happen when errors occur but the script continues without warning, causing hidden problems.
Step 2: Role of error handling
Error handling alerts the user immediately when something goes wrong, preventing unnoticed issues.
Final Answer:
It shows when something goes wrong instead of failing silently -> Option C
Quick Check:
Error handling prevents silent failures = D [OK]
Hint: Error handling alerts you to problems early [OK]
C. mkdir: cannot create directory '/root/testdir': Permission denied
Script finished
D. No output
Solution
Step 1: Analyze mkdir command
Creating a directory in /root usually requires root permission, so mkdir will fail with permission denied.
Step 2: Check error handling
Because mkdir fails, the || operator triggers the echo "Failed to create directory" message.
Final Answer:
Failed to create directory
Script finished -> Option A
Quick Check:
mkdir fails triggers echo = B [OK]
Hint: If command fails, || runs the error message [OK]
Common Mistakes:
Assuming mkdir succeeds without permission
Expecting no error message printed
Confusing command error output with echo message
4. Identify the error in this script snippet that tries to handle errors:
cp file1.txt /backup/
if [ $? -eq 0 ]
then
echo "Copy succeeded"
else
echo "Copy failed"
fi
medium
A. Missing semicolon after if condition
B. Incorrect use of $? for error checking
C. Missing quotes around file names
D. No error, script works correctly
Solution
Step 1: Check if statement syntax
The if condition [ $? -eq 0 ] is followed by a newline before 'then', which is valid bash syntax. No semicolon is required in this multi-line format.
Step 2: Verify other elements
$? correctly captures the exit status of cp. Quotes around file names/paths are optional here.
Final Answer:
No error, script works correctly -> Option D
Quick Check:
Multi-line if syntax valid without semicolon = C [OK]
Hint: Put ; or newline before then in if statements [OK]
Common Mistakes:
Thinking the if statement has a syntax error
Believing $? cannot be used for error checking
Assuming quotes are mandatory for file names here
5. You want to run a script that copies files and stops immediately if any copy fails, showing an error message. Which approach best prevents silent failures?
hard
A. Use set -e at the start and cp source dest || echo "Copy failed" for each copy
B. Ignore errors and continue copying all files
C. Use only cp source dest without checks
D. Redirect all errors to /dev/null to hide them
Solution
Step 1: Understand set -e behavior
set -e makes the script exit immediately if any command fails, preventing silent failures.
Step 2: Combine with error messages
Using cp source dest || echo "Copy failed" shows a clear error message when a copy fails before exiting.
Final Answer:
Use set -e at the start and cp source dest || echo "Copy failed" for each copy -> Option A
Quick Check:
set -e + error messages stop silent failures = A [OK]
Hint: Use set -e plus || echo for safe scripts [OK]
Common Mistakes:
Ignoring errors and continuing blindly
Not using set -e to stop on failure
Hiding errors by redirecting to /dev/null
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.