12

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?

Gnubie
  • 2,857
  • 1
  • 29
  • 29
  • _"..The ability to source a script with arguments is a bashism.."_ [Check here](http://unix.stackexchange.com/a/5027/66388) for more details. – Hastur Jan 21 '16 at 12:45

1 Answers1

6

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.

Amessihel
  • 355
  • 1
  • 11
  • 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