How can I skip the rest of a script without exiting the invoking shell, when sourcing the script?

Use return.

The return bash builtin will exit the sourced script without stopping the calling (parent/sourcing) script.

From man bash:

return [n]
Causes a function to stop executing and return the value specified by n to its caller. If n is omitted, the return status is that of the last command executed in the function body. … If return is used outside a function, but during execution of a script by the . (source) command, it causes the shell to stop executing that script and return either n or the exit status of the last command executed within the script as the exit status of the script.


You could simply wrap your script in a function and then use return the way you describe.

#!/bin/bash
main () {
    # Start of script
    if [ <condition> ]; then
        return
    fi
    # Rest of the script will not run if returned
}

main "$@"