I'm been having some weird problems with bash lately. While trying to simplify my script, I came up with this small piece of code:
$ o(){ echo | while read -r; do return 0; done; echo $?;}; o
0
$ o(){ echo | while read -r; do return 1; done; echo $?;}; o
1
return
should have exited the function without printing $?
, shouldn't it? Well, then I checked if I can return from a pipe alone:
$ echo | while read -r; do return 1; done
bash: return: can only `return' from a function or sourced script
The same happens without a while
loop:
$ foo(){ : | return 1; echo "This should not be printed.";}
$ foo
This should not be printed.
Is there something I'm missing here? A Google search brought nothing about this! My bash version is 4.2.37(1)-release on Debian Wheezy.
while
is not needed for reproduction? It distracts from the point.while
loop is a very common usage for a pipe withreturn
. The second example is more straight to the point, but it is something I don't believe anyone would ever use...