How to redirect stdin for bash source command

bash

I would like to source a file and redirect STDIN for that source. Is it possible?

Example, I have this file I wish to source:

# test.sh
export VALUE=SOMETHING

This works in a shell:

> source test.sh
> echo $VALUE
SOMETHING
>

Yet this doesn't work

> echo anything | source test.sh
> echo $VALUE

>

Is there some way this can be done, or is it because "source" runs in the current shell that it can't possibly redirect STDIN temporarily?

Best Answer

There is a good reason why this doesn't work:

echo anything | source test.sh

It is because the above is a pipeline. Consequently, source test.sh runs in a subshell. That means that any environment variables it creates are discarded when its execution completes.

The solution to your problem is:

 source test.sh < <(echo anything)

With this approach, source test.sh runs in the main shell. Its stdin is redirected from echo anything using process substitution.

The first < redirects stdin. The second < is part of the <(...) construct which creates a process substitution. At least one space between the first and second < is required.

Related Question