Interview Scripting (Bash, Groovy)

What does sourcing a script do differently from executing it? [Basic]

Answer

Sourcing runs the file in the current shell instead of starting a separate shell process. That means changes to variables, functions, shell options, and the working directory persist after the sourced file completes.

Technical explanation

It is useful for loading configuration or helper functions into an interactive session or another script.

It is not isolated, so a bad sourced script can overwrite variables, change set options, or exit the caller unless carefully written.

For libraries, avoid top-level destructive commands and expose functions that the caller can invoke deliberately.

Hands-on example

cat > lib.sh <<'EOF'

log() { printf '[%s] %s\n' "$(date +%H:%M:%S)" "$*"; }

export TOOL_REGION=ap-south-1

EOF

source ./lib.sh

log "region is $TOOL_REGION"

Preparing for an interview?

Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.

More Scripting (Bash, Groovy) interview questions

← All Scripting (Bash, Groovy) questions