문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top