在shell脚本中,可以使用 trap
命令来捕获异常并继续执行。下面是一个示例代码:
#!/bin/bash
# 定义异常处理函数
handle_error() {
echo "An error occurred. Continuing execution..."
}
# 设置异常处理函数
trap handle_error ERR
# 模拟一个可能发生异常的命令
echo "Trying to access a non-existent file..."
ls non_existent_file
# 继续执行后续命令
echo "Execution continued after handling the error."
在上面的示例中,trap handle_error ERR
表示在发生异常时调用 handle_error
函数。当执行 ls non_existent_file
命令时,由于文件不存在,会触发异常,然后执行 handle_error
函数。接着会继续执行后续的命令。
通过这种方式,即使在脚本执行过程中发生了异常,也可以捕获异常并继续执行后续的命令。