获取bash/ksh中命令的退出代码 [英] Get exit code for command in bash/ksh

查看:150
本文介绍了获取bash/ksh中命令的退出代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要编写这样的代码:

command="some command"

safeRunCommand $command

safeRunCommand() {
   cmnd=$1

   $($cmnd)

   if [ $? != 0 ]; then
      printf "Error when executing command: '$command'"
      exit $ERROR_CODE
   fi
}

但是此代码无法按照我想要的方式工作. 我在哪里弄错了?

But this code does not working the way I want. Where I made mistake?

推荐答案

下面是固定代码:

#!/bin/ksh
safeRunCommand() {
  typeset cmnd="$*"
  typeset ret_code

  echo cmnd=$cmnd
  eval $cmnd
  ret_code=$?
  if [ $ret_code != 0 ]; then
    printf "Error : [%d] when executing command: '$cmnd'" $ret_code
    exit $ret_code
  fi
}

command="ls -l | grep p"
safeRunCommand "$command"

现在,如果您看一下这段代码,我需要更改的几件事是:

Now if you look into this code few things that I changed are:

  • typeset的使用不是必需的,而是一种很好的做法.它将cmndret_code本地化为safeRunCommand
  • 没有必要使用ret_code,但这是将返回码存储在某个变量中(并尽快存储)的一种好习惯,这样您以后就可以像在printf "Error : [%d] when executing command: '$command'" $ret_code
  • 中那样使用它了.
  • 传递命令,并用引号引起来,例如safeRunCommand "$command".如果您不这样做,那么cmnd将仅获得值ls而不是ls -l.如果您的命令包含管道,则更为重要.
  • 如果要保留空格,可以使用typeset cmnd="$*"代替typeset cmnd="$1".您可以尝试两种方法,具体取决于命令参数的复杂程度.
  • 使用eval进行评估,以便包含管道的命令可以正常工作
  • use of typeset is not necessary but a good practice. It make cmnd and ret_code local to safeRunCommand
  • use of ret_code is not necessary but a good practice to store return code in some variable (and store it ASAP) so that you can use it later like I did in printf "Error : [%d] when executing command: '$command'" $ret_code
  • pass the command with quotes surrounding the command like safeRunCommand "$command". If you dont then cmnd will get only the value ls and not ls -l. And it is even more important if your command contains pipes.
  • you can use typeset cmnd="$*" instead of typeset cmnd="$1" if you want to keep the spaces. You can try with both depending upon how complex is your command argument.
  • eval is used to evaluate so that command containing pipes can work fine

注意:即使没有像grep这样的错误,也请记住某些命令将1作为返回码.如果grep找到了某些内容,它将返回0,否则返回1.

NOTE: Do remember some commands give 1 as return code even though there is no error like grep. If grep found something it will return 0 else 1.

我已经用KSH/BASH进行了测试.而且效果很好.让我知道您是否遇到运行此问题.

I had tested with KSH/BASH. And it worked fine. Let me know if u face issues running this.

这篇关于获取bash/ksh中命令的退出代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆