Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop processing sourced file and continue

When writing bash that sources another file, sometimes I want to skip processing if some conditions are true. For now, I've been either:

  1. Wrapping the entire sub file in nested if statements
  2. Wrapping the call to the source file in nested if statements

Both of these strategies have some drawbacks. It'd be so much better if I could write my scripts with this code style:

main.sh

echo "before"
. other
echo "after"

other.sh

# guard
if true; then
  # !! return to main somehow
fi
if true; then
  # !! return to main somehow
fi

# commands
echo "should never get here"

Is there a way to do this so that the echo "after" line in main gets called?

like image 222
Dane O'Connor Avatar asked Mar 03 '14 17:03

Dane O'Connor


1 Answers

Yes, you could return:

if true; then
  return
fi

Quoting 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.

like image 79
devnull Avatar answered Nov 15 '22 11:11

devnull