Reputation: 5434
How would you exit out of a function if a condition is true without killing the whole script, just return back to before you called the function.
Example
# Start script
Do scripty stuff here
Ok now lets call FUNCT
FUNCT
Here is A to come back to
function FUNCT {
if [ blah is false ]; then
exit the function and go up to A
else
keep running the function
fi
}
Upvotes: 198
Views: 243107
Reputation: 1
I found the above examples incomplete. And tbh confusing.
function test() { [[ 5 -eq 5 ]] && return 0 || return 1 ; } ; test ; echo $?
function test() { [[ 5 -eq 3 ]] && return 0 || return 1 ; } ; test ; echo $?
will print
0
1
Upvotes: 0
Reputation: 1792
My use case is to run the function unless it's already running. I'm doing
mkdir /tmp/nice_exit || return 0
And then at the end of the function
rm -rf /tmp/nice_exit
Upvotes: -1
Reputation: 5297
If you want to return from an outer function with an error without exit
ing you can use this trick:
do-something-complex() {
# Using `return` here would only return from `fail`, not from `do-something-complex`.
# Using `exit` would close the entire shell.
# So we (ab)use a different feature. :)
fail() { : "${__fail_fast:?$1}"; }
nested-func() {
try-this || fail "This didn't work"
try-that || fail "That didn't work"
}
nested-func
}
Trying it out:
$ do-something-complex
try-this: command not found
bash: __fail_fast: This didn't work
This has the added benefit/drawback that you can optionally turn off this feature: __fail_fast=x do-something-complex
.
Note that this causes the outermost function to return 1.
Upvotes: 8
Reputation: 6044
Use:
return [n]
From help return
return: return [n]
Return from a shell function. Causes a function or sourced script to exit with the return value specified by N. If N is omitted, the return status is that of the last command executed within the function or script. Exit Status: Returns N, or failure if the shell is not executing a function or script.
Upvotes: 273
Reputation: 22157
Use return
operator:
function FUNCT {
if [ blah is false ]; then
return 1 # or return 0, or even you can omit the argument.
else
keep running the function
fi
}
Upvotes: 44