2

In bash and other shells, I can make same variables have "line scope" by defining it just before a command.

CXX=clang++ ./script.bash

Which I prefer over

export CXX=clang++
./script.bash

because the former doesn't contaminate the environment.

How can I do the same with variables set by source and achieve the same "line scope" effect?

The equivalent of:

source env.source  # defines a bunch of vars
./script.bash
??? ./script.bash
alfC
  • 133

1 Answers1

3

Use a sub-shell:

( source env.source && ./script.bash )

The environment inside the sub-shell is destroyed when the sub-shell terminates.

Or, in bash, set BASH_ENV for the script:

BASH_ENV=./env.source ./script.bash

The BASH_ENV variable comes into effect for non-interactive shells (i.e. scripts). If the variable is set to the pathname of a dot-script, that dot-script will be sourced before the body of the main script runs. Note that the dot-script will not be searched for in $PATH when using BASH_ENV, which is different from when using . or source, so you need to provide the complete path (relative or absolute).

("dot-script" == a script that is sourced with the . (dot) utility, which is also known as source in bash.)

Kusalananda
  • 333,661