Search code examples
bash

bash script: how to "exit" from sourced script, and allow to work non sourced?


I have a script that I'd like people to source, but optionally so. So they can run it with or without sourcing it, it's up to them.

e.g. The following should both work:

$ . test.sh
$ test.sh

The problem is, test.sh contains exit statements if incorrect args are passed in. If someone sources the script, then the exit commands exit the terminal!

I've done a bit of research and see from this StackOverflow post that I could detect if it's being sourced, and do something different, but what would that something different be?


Solution

  • The normal way to exit from a sourced script is simply to return (optionally adding the desired exit code) outside of any function. Assuming that when run as a command we have the -e flag set, this will also exit from a shell program:

    #!/bin/sh -eu
    
    if [ $# = 0 ]
    then
        echo "Usage $0 <argument>" >&2 
        return 1
    fi
    

    If we're running without -e, we might be able to return || exit instead.