Search code examples
shellgrepexit-code

grep command exit code for unmatched patterns


i have written a shell scripts which runs crontab - l command

To make it more easy to use i have also given the user an ability to pass a command line argument to the script which will act like a pattern input for the grep command, so that the user can filter out all the stuffs which he/she doesn't need to see.

here's the script:-

  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

this is how i run it

$ ./DisplayCrontab.sh

Now if i don't pass any command line argument it'll show me the complete crontab

If i pass any garbage pattern which doesn't exists in the crontab it'll show me the following message :-

 grep command on crontab -l was not successful

But even if i pass a pattern which does exist in a couple of lines in crontab, i'm getting this kind of output:-

#matching lines
#matching lines
#matching lines

grep command on crontab -l was not successful

Why am i getting grep command not successful at the bottom?, how can i get rid of it?

Is there anything wrong with the script?


Solution

  • You're capturing the exit code before the execution, should be:

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

    To test this code use numeric operators:

    [[ $rc -ne 0 ]]
    

    Grep man:

    Normally, the exit status is 0 if selected lines are found and 1 otherwise. But the exit status is 2 if an error occurred