I’m having trouble understanding the behavior of the return built-in in Bash. Here is a sample script.
#!/bin/bash
dostuff() {
date | while true; do
echo returning 0
return 0
echo really-notreached
done
echo notreached
return 3
}
dostuff
echo returncode: $?
The output of this script is:
returning 0
notreached
returncode: 3
If, however, the date | is removed from line 4, the output is as I expected:
returning 0
returncode: 0
It seems like the return statement as used above is acting the way I thought the break statement ought to behave, but only when the loop is on the right hand side of a pipe. Why is this the case? I couldn’t find anything to explain this behavior in the Bash man page or online. The script acts the same way in Bash 4.1.5 and Dash 0.5.5.
In the
date | while ...scenario, that while loop is executed in a subshell due to the presence of the pipe. Thus, the return statement breaks the loop and the subshell ends, leaving your function to carry on.You’ll have to reconstruct the code to remove the pipeline so that no subshells are created: