grep命令用于不匹配模式的退出代码

时间:2014-07-14 06:51:21

标签: shell grep exit-code

我编写了一个运行crontab - l命令

的shell脚本

为了使它更容易使用,我还让用户能够将命令行参数传递给脚本,这将作为grep命令的模式输入,以便用户可以过滤掉所有的东西他/她不需要看。

这是脚本: -

  1 #!/bin/bash
  2 if [[ $1 == "" ]]; then
  3         echo -e "No Argument passed:- Showing default crontab\n"
  4         command=$(crontab -l 2>&1)
  5         echo "$command"
  6 else
  7         rc=$?
  8         command=$(crontab -l | grep -- "$1" 2>&1)
  9         echo "$command"
 10         if [[ $rc != 0 ]] ; then
 11                 echo -e "grep command on crontab -l was not successful"
 12         fi
 13 fi

这是我如何运行它

$ ./DisplayCrontab.sh

现在如果我没有传递任何命令行参数,它将显示完整的crontab

如果我传递了crontab中不存在的任何垃圾模式,它将显示以下消息: -

 grep command on crontab -l was not successful

但即使我传递了一个在crontab中存在几行的模式,我也得到了这种输出: -

#matching lines
#matching lines
#matching lines

grep command on crontab -l was not successful

为什么我的grep命令在底部没有成功?我怎么能摆脱它?

脚本有什么问题吗?

1 个答案:

答案 0 :(得分:2)

您在执行前捕获退出代码,应该是:

command=$(crontab -l | grep -- "$1" 2>&1)
rc=$?

要测试此代码,请使用数字运算符:

[[ $rc -ne 0 ]]

Grep man:

  

通常,如果找到选定行,则退出状态为0   否则为1。但如果发生错误,退出状态为2

相关问题