0

I am trying to use set -e in my shell script to exit the script when an error occurs.

set -e causes my script to exit when grep doesn't find the pattern in a file. In some cases, I am okay if pattern is not found but I want script to continue execution instead of aborting. I still want the script to abort if file is not present or any other error but script should continue only if pattern is not found.

I know I can replace the grep with sed to avoid such errors but I am keeping it as last option because grep is widely used in my script and would require a rework.

Is there any option by which I can exempt grep from set -e or customize return codes of grep?

Note: I need to use set -e, I can't remove it because bash expert in my team wants to use it.

Nachiket Kate
  • 8,473
  • 2
  • 27
  • 45
  • 5
    `grep .... || :` or `grep ... || true` Also `set -e` has *many* quirks and cases where it doesn't apply so make sure the "bash expert" knows that it falls over in many cases (and many people don't recommend using it, see [Bash FAQ 105](http://mywiki.wooledge.org/BashFAQ/105) for example). – Etan Reisner Nov 12 '15 at 18:59
  • Could you please elaborate a little? I forgot to mention that script should exist if file is not found or doesn't have permissions etc. It should continue only in case of pattern not found. I will update the question. – Nachiket Kate Nov 12 '15 at 19:02
  • You can't "silence" *some* errors and not others with a simple tweak. You can check the return code from `grep` and re-exit when they are ones you care about (but that requires `grep` to distinguish for you and I would bet it doesn't). Which means you get to write your own extended tests to ensure the other things you care about are true. – Etan Reisner Nov 12 '15 at 19:06
  • `set -e` is probably not a good idea. Many constructs intentionally depend on non-zero return status. It's probably better to just add `|| additional_tests_where_necessary || { echo "error message"; exit 1; }` where necessary. – 4ae1e1 Nov 12 '15 at 19:07
  • Thanks for comments. It looks I need a little rework :) – Nachiket Kate Nov 12 '15 at 19:09
  • since you seem to regard this as answered, it would help if you would post your own answer – chrisdowney Nov 12 '15 at 19:24
  • See also http://stackoverflow.com/questions/38802963/grep-a-file-out-of-another-file-works-only-one-way-why/38805678#38805678 – tripleee Aug 21 '16 at 11:44

0 Answers0