I would like to use git grep to check for banned strings in the repo.
if git grep --full-name --extended-regexp --line-number 'bad|words'
then
echo has bad words
else
echo does not have bad words
fi
A problem with this is that if the git grep
command fails for another reason, for example being malformed, the script will report that there are no bad words, but actually it doesn't know whether or not there are bad words in the repo so it's not safe to branch that way.
I want to know whether git grep
failed because it didn't find anything, or because it had another error that made it exit without even trying to find anything.
I would like git grep
to return the same exit status for bad words as it does for errors. Only if it confirms that there are no bad words, should it return a unique exit status code.
Check the exit code. As there're 3 variants (found, not found, error) you cannot just use if
/else
.
git grep --full-name --extended-regexp --line-number 'bad|words'
rc=$? # save exit code
if [ $rc -eq 0 ]
then
echo has bad words
elif [ $rc -eq 1 ]
then
echo does not have bad words
else
echo error >&2
fi
exit $rc # return the exit code back to the caller