Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

grep has a bad interaction with set -e, since it (infuriatingly) exits with 1 if no lines are matched.


Well, otherwise `if grep "line" $file; then` wouldn't work, which in my opinion is the primary use case for grep in scripts.

I'd still prefer a `grep <args> || true` over not having `set -e` for the whole file.


You can `set +e` before and `set -e` after every such command. I indent those commands to make it look like a block and to make sure setting errexit again isn’t forgotten.


But you probably still want an error if the input file does not exist. To handle grep correctly in a robust manner requires many lines of boilerplate, set +e, storing $?, set -e, distinguishing exit values 0, 1, and 2.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: