Home > front end >  bash echo does not work after grep returns nothing
bash echo does not work after grep returns nothing

Time:12-24

I understand that people generally use grep in Linux command prompt (not in a script). I happen to put grep in a script and run into a strange case. If the grep command returns nothing, the next line echo does not work. Below is the script.

grep "abc" /home/testuser/myapp.log
echo "abc"

Is this the normal behavior of grep? If yes, why?

CodePudding user response:

You can use the following command to echo with grep:

printf "%s\n" "$(grep -o "abc" /home/testuser/myapp.log)"

References

CodePudding user response:

It would appear that set -e is enabled in your script.

Normally the exit status of grep is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. Note however, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. In your case, if abc is not found in /home/testuser/myapp.log, grep will return 1.

The bash shell will normally execute the next line in your script, i.e. echo "abc" even if grep returns an exit status of 1. However if set -e is enabled, bash will not execute any more lines in your script.

From the bash manpage:

-e      Exit immediately if a pipeline (which may consist of a single simple command), a list, or  a  compound  command
        (see  SHELL GRAMMAR above), exits with a non-zero status.  The shell does not exit if the command that fails is
        part of the command list immediately following a while or until keyword, part of the test following the  if  or
        elif  reserved words, part of any command executed in a && or || list except the command following the final &&
        or ||, any command in a pipeline but the last, or if the command's return value is being inverted with !.  If a
        compound  command  other  than a subshell returns a non-zero status because a command failed while -e was being
        ignored, the shell does not exit.  A trap on ERR, if set, is executed before the shell exits.  This option  ap‐
        plies  to  the  shell  environment  and each subshell environment separately (see COMMAND EXECUTION ENVIRONMENT
        above), and may cause subshells to exit before executing all the commands in the subshell.
   
        If a compound command or shell function executes in a context where -e is being ignored, none of  the  commands
        executed within the compound command or function body will be affected by the -e setting, even if -e is set and
        a command returns a failure status.  If a compound command or shell function sets -e while executing in a  con‐
        text  where -e is ignored, that setting will not have any effect until the compound command or the command con‐
        taining the function call completes.
  • Related