2

These questions address the functionality of source: What is the difference between executing a Bash script vs sourcing it? What does 'source' do?

but I'm confused as to why calling source in a script passes the script's arguments. E.g. I have these 2 scripts:

caller.sh

source sourced.sh
source sourced.sh ""

sourced.sh

echo [$*]

When I do

./caller.sh arg1 arg2

I get

[arg1 arg2]
[]

"arg1 arg2" are passed to sourced.sh even though I didn't specify source sourced.sh $*.

Why?

I found that appending "" prevents the arguments from being passed. Is this the recommended way to prevent arguments passed?

  • "..The ability to source a script with arguments is a bashism.." Check here for more details. – Hastur Jan 21 '16 at 12:45
4

source allows you to execute a command in the current context (arguments $* are part of context).

The second source call overwrites these arguments. Note it overwrites them only for the call, they are restored right after.

  • Thanks, Amessihel. Is the second call the recommended way to omit the arguments? – Gnubie Jan 21 '16 at 15:43
  • If you want to execute this command to a new context (only exported variables will be accessible), better run it without source. Else, I don't know if there is a good practice to prevent this bash specific behaviour... Yours seems fine. – Amessihel Jan 21 '16 at 17:10
  • I need to use source because the real sourced.sh sets some env variables (and I can't modify it to export them as it's a published file). – Gnubie Jan 21 '16 at 18:46
  • If you know what variables you need, you can also pass them this way : VAR=VAL VAR2=VAL2 sourced.sh instead of source. – Amessihel Jan 22 '16 at 16:07

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.