How to redirect stdin for bash source command?
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.