-
Notifications
You must be signed in to change notification settings - Fork 1.9k
SC2104
Eisuke Kawashima edited this page Jul 29, 2025
·
3 revisions
foo() {
if [[ -z $1 ]]
then
break
fi
echo "Hello $1"
}foo() {
if [[ -z $1 ]]
then
return 1
fi
echo "Hello $1"
}break or continue are used to abort or continue a loop, and are not the right way to exit a function. Use return instead.
The break or continue may be intended for a loop that calls the function:
# Rarely valid
foo() { break; echo $?; }
while true; do foo; doneThis is undefined behavior in POSIX sh. Different shells do different things.
When the function is called from a loop:
-
kshkeeps going and$?is 0. -
bashversion 4.4+ prints an error "break: only meaningful in a `for', `while', or `until' loop", the function keeps going, and$?is 0. -
bashversions before 4.4, will return from the function, break the loop calling the function, or exit a subshell if there's one in between. -
dash, BusyBoxash: like above.
When the function is not called from a loop:
- All
bashversions print an error "break: only meaningful in a `for', `while', or `until' loop", the function keeps going, and$?is 0. -
ksh,dashandashsilently keep going and$?is 0.
Due to the many different implementations, many of which are not helpful, it's recommended to use proper flow control. A typical solution is making sure the function returns success/failure, and calling myfunction || break in the loop.