Reputation: 15
Prevent grep returning an error when input doesn't match. I would like it to keep running and not exit with exit code: 1
set -euo pipefail
numbr_match=$(find logs/log_proj | grep "$name" | wc -l);
How could I solve this?
Upvotes: 0
Views: 1074
Reputation: 22301
I don't know why you are using -e
and pipefail
when you don't want to have this behaviour. If your goal is just to treat exit code 2 (by grep) as error, but exit code 1 as no-error, you could write a wrapper script around grep
, which you
call instead of grep:
#!/bin/bash
# This script behaves exactly like grep, only
# that it returns exit code 0 if there are no
# matching lines
grep "$@"
rc=$?
exit $((rc == 1 ? 0 : rc))
Upvotes: 0
Reputation: 189749
In this individual case, you should probably use
find logs/log_proj -name "*$name*" | wc -l
More generally, you can run grep
in a subshell and trap the error.
find logs/log_proj | ( grep "$name" || true) | wc -l
... though of course grep | wc -l
is separately an antipattern;
find logs/log_proj | grep -c "$name" || true
Upvotes: 1