【问题标题】:Error handling in unix shell kshunix shell ksh 中的错误处理
【发布时间】:2015-12-23 07:50:51
【问题描述】:

任何人都可以在下面指导文档或解释

  • 如何在 ksh 中使用错误处理。
  • Unix 如何处理未处理的错误(如错误发生在 下标等)。

【问题讨论】:

    标签: unix ksh


    【解决方案1】:

    来自kshman 页面。

    未处理的错误

    shell 检测到的错误(例如语法错误)会导致 shell 返回非零退出状态。如果正在使用外壳 非交互式,然后执行 shell 文件被放弃 除非错误发生在内部 subshel​​l,在这种情况下subshel​​l放弃

    错误处理

    基本上 检查退出/返回代码来处理错误:

    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
    

    外壳返回 最后执行的命令退出状态 (另请参见上面的退出命令)。由 shell 检测到的运行时错误通过打印命令或函数名称和 错误情况。如果行号 发生的错误大于一,则行号也打印在命令或函数之后的方括号([])中 名字。

    【讨论】:

    • 谢谢。但是如果我们想在函数内部处理错误怎么办。是否可以像在其他一些语言中那样进行“try-catch”检查?
    • 嗨@klashxx:我的意思是-我有一个用脚本Y编写的函数X,如果X中发生UNHANDLED错误,我不想退出Y。而是退出X
    • 您必须测试函数中执行的每个command / cmd,基本规则:exit > 0 意味着错误处理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多