Grep is a ubiquitous tool for searching plain text in *nix systems. It is so ubiquitous that the documentation for select-string in PowerShell mentions grep and the Oxford English Dictionary added grep as a noun and a verb in 2003.
While grep is incredibly well known, that doesn’t prevent it from having odd quirks that left me stuck debugging a script for hours.
If grep does not find the specified pattern, it exits with an exit code of 1 and kills the running script.
> echo "foo" | grep --count "bar"
0
> echo $?
1
> echo "foobar" | grep --count "bar"
1
> echo $?
0
It took me ages to recognize that my script was failing because of grep. I included the count flag because I needed the count for future logic, and I saw the correct count coming out but couldn’t understand why the script stopped executing there.
In hindsight, it was obvious, but it took me a while to get there.
The trick to using grep in a script that might return no results is adding an or true.
> echo "foo" | grep --count "bar" || true
0
> echo $?
0
> echo "foobar" | grep --count "bar" || true
1
> echo $?
0