Skip to main content
3 of 5
added 58 characters in body

grep behaviour is different in subshell

I met interesting issue while working with this code. Why the same bash code produce different result depends of interactive shell or subshell? Make all-zeros file with name 'yourfile'.

a@L:~$ truncate -s 1K your_file 

Interactive shell example

a@L:~$ tr -d '\0' <your_file | grep -am 1 ^ ; echo $? 1 

The same code but using subshell

a@L:~$ bash -c 'tr -d '\0' <your_file | grep -am 1 ^ ; echo $?' 0 

And also interesting fact. I changed original example by adding -a option ("equivalent to --binary-files=text") because without this option interactive shell works but subshell:

a@L:~$ bash -c 'tr -d '\0' <your_file | grep -m 1 ^ ; echo $?' grep: (standard input): binary file matches 0 

P.S. I use bash 5.2.37(1)-release from Ubuntu 25.04