egrep: empty (sub)expression : Unexpected behaviour for bash Loop on Mac I have the filling simplified script on Mac OS X 10.12 :

#!/usr/bin/env bash

echo "=&gt; BASH_VERSION = $BASH_VERSION"
function testForLoopMac {
local file
for file
do
    echo File=$file
done | egrep "$file"
}

function testForLoopMacBis {
local file
for file
do
    echo File=$file
done | egrep "$file|OK"
}

testForLoopMac $@

testForLoopMacBis $@


But the result when I run is :

$ testForLoopMac.sh example.pdf 
=&gt; BASH_VERSION = 3.2.57(1)-release
File=example.pdf
egrep: empty (sub)expression


On Debian/Ubuntu Linux, the result is :

$ testForLoopMac.sh example.md 
=&gt; BASH_VERSION = 4.3.30(1)-release
File=example.md
File=example.md


Edit : With bash4 on Mac OSX 10.12 :

I changed the shebang to #!/usr/bin/env bash4 and the result is the same :

$ testForLoopMac.sh example.md 
=&gt; BASH_VERSION = 4.4.12(1)-release
File=example.md
egrep: empty (sub)expression


Edit: Thanks to you guys I understand the behavior difference on Linux or BSD egrep is because that at the time of the egrep execution the variable can be empty.

I'm going the use therefore, the following regExp :

egrep "File=|OK"

Thanks again :)
The shell expands the subexpression $file on the right hand side of the pipe before the variable has any value. So in both functions egrep is actually called with the empty string in place of $file. The first function doesn't throw an error because an empty pattern is a valid parameter for egrep both on macOS and on Linux. In the second fucntion the difference comes into play because the empty subexpression causes BSD egrep (the one used on macOS) to throw an error.

Example:

echo foo | egrep "|foo"
egrep: empty (sub)expression


as another example with $file having no value

echo foo | egrep "$file|foo"
egrep: empty (sub)expression


So, as a workaround in your function use:

egrep -e "$file" -e 'OK'


I have no idea why you are using egrep when you are looking for fixed strings.