Skip to content
Advertisement

Script terminates when storing grep -c output when value is 0

I am trying to check if a file has CR line feed and store the result 0 or 1 into a variable.

Here is my command that runs inside a script.

isCR="$(file ${fileName} | grep -c 'with CR line terminators')"

The script runs until the previous line and doesn’t run this line but terminates abruptly.

Inside an echo statement it works perfectly.

echo "isCR=$(file ${fileName} | grep -c 'with CR line terminators')"

This prints isCR=0 or isCR=1 depending on the file I use.

But just storing the value into variable isCR doesn’t work. I am confused what am i missing here. Any help is appreciated.

Advertisement

Answer

Using set -e (aka set -o errexit) tells the shell to exit whenever any command returns a nonzero exit status.

grep returns a nonzero exit status when it finds no matches.

Thus, when using bash -e, set -e, set -o errexit, an ERR trap which triggers an exit, or similar configuration, isCR="$(file ${fileName} | grep -c 'with CR line terminators')" will terminate your script because the nonzero exit status from the grep command is passed through as the exit status of the command as a whole.

By contrast, echo "$(false)" does not because its exit status is that of echo, not that of false; this holds true when the command returning the failed exit status is grep as well.


If you want to use set -e but bypass its behavior for this specific line, consider:

isCR="$(file ${fileName} | grep -c 'with CR line terminators')" || [[ $isCR ]]

The || [[ $isCR ]] will make the line as a whole have a truthy result even if grep returns false, so long as it emitted a nonzero number of characters.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement