I suspect you have 2 versions of bash
on your system, and that when you're calling bash -c ''
, you're invoking a different version. That or your code was altered when you created the question.
As for why I think this, your code does not work on my system:
$ test() { echo foo |sed -r s/.*(.)/\\1/g; }
bash: syntax error near unexpected token `('
The issue is that you have no quotes around the sed
expression, so bash is trying to interpret it as a shell expression. I'm guessing this behavior changed between bash versions, and that your login shell is a different version of bash
than whatever is in your $PATH
when calling bash -c ''
.
You can check this by doing:
$ echo $SHELL
$ which bash
Another possible cause would be if you have some shell options set which are changing the behavior of bash's expression evaluation, and these options are not being used by the bash -c ''
.
As for how to fix the issue, when I properly quote the sed
expression, it works fine:
$ test() { echo foo | sed 's/.*\(.\)/\1/g'; }
$ export -f test
$ bash -c 'test'
o
(Note: I had to slighly tweak the sed
command as it's not a valid command for my version of sed
)