ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Error Handling in a Multi-Step Shell Script

Shell (sh)

Goal -- WPM

Ready
Exercise Algorithm Area
1#!/bin/sh
2
3# Script demonstrating robust error handling in a multi-step process.
4# Uses 'set -e' and explicit checks for critical operations.
5
6# --- Configuration ---
7TARGET_DIR="/tmp/my_processing_area"
8SOURCE_FILE="/etc/hosts"
9PROCESSED_FILE="$TARGET_DIR/hosts.processed"
10
11# --- Helper Functions ---
12
13# Function to perform a simulated processing step.
14# Takes input and output filenames as arguments.
15_simulate_processing() {
16local input_file="$1"
17local output_file="$2"
18
19echo "Simulating processing: '$input_file' -> '$output_file'"
20
21# Simulate a potential failure condition (e.g., if input file is missing)
22if [ ! -r "$input_file" ]; then
23echo "Error: Input file '$input_file' not found or not readable." >&2
24return 1 # Indicate failure
25fi
26
27# Simulate the actual processing: copy and append a line.
28cp "$input_file" "$output_file"
29if [ $? -ne 0 ]; then
30echo "Error: Failed to copy '$input_file' to '$output_file'." >&2
31return 1 # Indicate failure
32fi
33
34echo " Appended processed data marker." >> "$output_file"
35if [ $? -ne 0 ]; then
36echo "Error: Failed to append data marker to '$output_file'." >&2
37return 1 # Indicate failure
38fi
39
40echo "Processing step completed successfully."
41return 0 # Indicate success
42}
43
44# --- Main Execution ---
45
46# Exit immediately if a command exits with a non-zero status.
47# This is a primary mechanism for error handling.
48set -e
49
50echo "Starting multi-step script..."
51
52# Step 1: Create the target directory.
53echo "Creating target directory: $TARGET_DIR"
54mkdir -p "$TARGET_DIR"
55# 'set -e' will cause the script to exit if mkdir fails.
56
57# Step 2: Copy the source file to the target directory.
58# We can also add explicit checks for clarity or more specific error messages.
59echo "Copying source file to target directory..."
60cp "$SOURCE_FILE" "$TARGET_DIR/"
61# 'set -e' handles failure here. If we wanted a custom message:
62# cp "$SOURCE_FILE" "$TARGET_DIR/" || { echo "Error: Failed to copy '$SOURCE_FILE'." >&2; exit 1; }
63
64# Step 3: Process the copied file using the helper function.
65echo "Performing simulated processing on the copied file..."
66if ! _simulate_processing "$TARGET_DIR/$(basename $SOURCE_FILE)" "$PROCESSED_FILE"; then
67# If _simulate_processing returns non-zero, this block is executed.
68echo "Script aborted due to processing failure." >&2
69exit 1 # Explicit exit, though _simulate_processing already returned 1
70fi
71
72# Step 4: Verify the processed file exists.
73echo "Verifying the processed file..."
74if [ ! -f "$PROCESSED_FILE" ]; then
75echo "Error: Processed file '$PROCESSED_FILE' was not created." >&2
76exit 1
77fi
78
79echo "Script completed successfully. Processed file is at: $PROCESSED_FILE"
80
81exit 0
Algorithm description viewbox

Error Handling in a Multi-Step Shell Script

Algorithm description:

This script demonstrates essential error handling in shell scripting. It performs a series of operations (directory creation, file copying, simulated processing) and includes checks after each critical step. The `set -e` option ensures that the script will exit immediately if any command fails. Additionally, explicit checks using `if ! command; then ... fi` are used for custom error messages and more granular control, especially for function return values. This pattern is fundamental for writing reliable shell scripts.

Algorithm explanation:

The script utilizes two primary methods for error handling. First, `set -e` is invoked at the beginning. This option causes the shell to exit immediately if any command fails (returns a non-zero exit status). This provides a baseline level of safety, preventing subsequent commands from running in an invalid state. Second, explicit checks are performed using `if ! command; then ... fi` or by checking the return status of functions. For instance, the `_simulate_processing` function returns 1 on failure, and the main script checks this return value. If the function fails, the script prints a custom error message and exits. This combination of `set -e` and explicit checks allows for both automatic termination on general errors and tailored error reporting for specific critical operations. The time complexity is O(N*M) where N is the number of steps and M is the average time for each step. Space complexity is O(1) for the script itself.

Pseudocode:

1. Set the shell option `set -e` to exit on error.
2. Define configuration variables (directory, source file, output file).
3. Define a helper function `_simulate_processing` that takes input and output filenames:
    a. Check if the input file exists and is readable. If not, print an error and return 1.
    b. Copy the input file to the output file. Check the return status of `cp`. If it fails, print an error and return 1.
    c. Append a marker to the output file. Check the return status of `echo`. If it fails, print an error and return 1.
    d. Print a success message and return 0.
4. In the main execution block:
    a. Print a starting message.
    b. Create the target directory using `mkdir -p`. `set -e` handles failure.
    c. Copy the source file to the target directory using `cp`. `set -e` handles failure.
    d. Call `_simulate_processing` with the appropriate filenames.
    e. If `_simulate_processing` returns a non-zero status, print an error and exit with status 1.
    f. Verify that the processed output file exists. If not, print an error and exit with status 1.
    g. Print a success message and exit with status 0.