To handle errors in a shell script, you can use conditional statements to check the exit status of commands and take appropriate actions based on whether they succeed or fail. Here's how you can enhance the previous script to include error handling:
Example Shell Script with Error Handling
#!/bin/bash
POD_NAME="my-pod"
# Function to handle errors
handle_error() {
echo "Error: $1"
exit 1
}
# Wait for the pod to be ready
echo "Waiting for pod $POD_NAME to be ready..."
if ! kubectl wait --for=condition=Ready pod/$POD_NAME --timeout=60s; then
handle_error "Pod $POD_NAME did not become ready in time."
fi
# Wait for the pod to be running
echo "Waiting for pod $POD_NAME to be running..."
if ! kubectl wait --for=condition=Running pod/$POD_NAME --timeout=60s; then
handle_error "Pod $POD_NAME did not start running in time."
fi
echo "Pod $POD_NAME is ready and running!"
Explanation
-
Error Handling Function:
- The
handle_errorfunction takes a message as an argument, prints it, and exits the script with a non-zero status.
- The
-
Conditional Execution:
- The
if !construct checks the exit status of thekubectl waitcommand. If the command fails (returns a non-zero status), it calls thehandle_errorfunction with a relevant message.
- The
-
Clear Messages:
- Each error message provides context about which condition failed, making it easier to diagnose issues.
Benefits
- Graceful Exit: The script exits cleanly with an error message if any command fails.
- Debugging: Clear error messages help in identifying what went wrong during execution.
- Maintainability: The structure makes it easy to add more conditions or modify error handling as needed.
Summary
By incorporating error handling into your shell script, you can create a more robust and user-friendly experience when managing Kubernetes resources. If you have further questions or need clarification, feel free to ask!
