# Determine if a script was sourced or executed

Bash only allows `return` in a function or at the top level of a sourced script. We can call it in a subshell and use the exit code to determine if the script is being sourced or not.

```bash
(return 0 2>/dev/null) && sourced=1 || sourced=0
```

If all we want to do is to halt execution at some point if we're sourcing the script, we can use the simpler `return 0 2>/dev/null` as a short-circuit.

```bash
#!/usr/bin/env bash

_a_function() {
  echo "useful stuff"
}

return 0 2>/dev/null

echo "I'll only print when script is executed"
_a_function
```

Example usage:

```bash
source ./script.sh
# _a_function now available for use
_a_function
# useful stuff

. ./script
# I'll only print when script is executed
# useful stuff
```

Source: [stackoverflow](https://stackoverflow.com/a/28776166)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://notes.eliasnorrby.com/bash/sourced-or-executed.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
