unix 中的错误处理 shell ksh

Error handling in unix shell ksh

谁能指导一下文档或在下面解释一下

来自 ksh man 页面。

未处理的错误

Errors detected by the shell, such as syntax errors, cause the shell to return a non-zero exit status. If the shell is being used non-interactively, then execution of the shell file is abandoned UNLESS the error occurs inside a subshell in which case the subshell is abandoned.

错误处理

基本上 检查 exit/return 错误处理代码:

if [ $exit_code != 0 ]; then
  # Your error handler
fi

例子

test_handler() {
  ls file_not_present
  if [ $? -eq 2 ]; then 
    echo "Handler for No such file or directory"
  elif [ $? -ne 0]; then
    echo "Handler for any other exception"
  else
    echo "Succesful execution"
  fi
}

抛出:

ls: cannot access non_file: No such file or directory
Handler for No such file or directory

但是如果命令没有退出:

test_handler() {
  l file_not_present
  if [ $? -eq 2 ]; then 
    echo "Handler for No such file or directory"
  elif [ $? -ne 0 ]; then
    echo "Handler for any other exception"
  else
    echo "Succesful execution"
  fi
}

输出将是:

l: not found [No such file or directory]
Handler for any other exception

The shell returns the exit status of the last command executed (see also the exit command above). Run time errors detected by the shell are reported by printing the command or function name and the error condition. If the line number that the error occurred on is greater than one, then the line number is also printed in square brackets ([]) after the command or function name.