Header Ads

How to handle exception on shell script?

 The process of gracefully handling errors and unexpected situations that may occur during script execution is known as exception handling in shell scripts. Here are a few examples of how to handle exceptions in shell scripts:

1. Exit codes are used by shell scripts to indicate whether a command or function succeeded or failed. An exit code of 0 indicates success, while codes other than zero indicate errors. The 'if" statement can be used to check the exit code of a command or function and then take appropriate action based on the result.

Example:

bash
if grep -q "pattern" file.txt; 
then 
    echo "Pattern found." 
else 
    echo "Pattern not found." 
fi

2. The 'set -e' option instructs the shell to exit immediately if a command returns a non-zero status. This is useful if you want your script to stop running as soon as an error occurs.

Example:

bash
#!/bin/bash 
set -e 
command1 
command2 
command3

In this example, if 'command1' fails, the script will immediately exit without executing 'command2' or 'command3'.

3. Using 'trap' to handle signals: The trap command allows you to set up a function to be called when the shell receives a specific signal. This can be used to deal with unexpected situations like a user pressing 'Ctrl-C' or the script running out of memory.

Example:

bash
#!/bin/bash
# Handle Ctrl-C 
trap ctrl_c INT 
function ctrl_c() { 
    echo "Script interrupted." 
    exit
}
# Run the script 
command1 
command2 
command3

In this example, the ctrl_c function will be called if the user presses Ctrl-C while the script is running.

  1. Using set -u option to treat unset variables as an error: The set -u option causes the shell to treat unset variables as an error and exit. This can be useful in preventing errors caused by typos or missing variables.

Example:

bash
#!/bin/bash 
set -u 
echo $VAR

In this example, if the VAR variable is not set, the script will exit with an error.

No comments

Powered by Blogger.