13

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?

1
  • 1
    "..The ability to source a script with arguments is a bashism.." Check here for more details.
    – Hastur
    Commented Jan 21, 2016 at 12:45

1 Answer 1

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.

4
  • Thanks, Amessihel. Is the second call the recommended way to omit the arguments?
    – Gnubie
    Commented Jan 21, 2016 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
    Commented Jan 21, 2016 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
    Commented Jan 21, 2016 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
    Commented Jan 22, 2016 at 16:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .