Alex
Alex

Reputation: 1205

Providing no arguments to sourced script

I have a bash script that can be "configured", as it sources the file located at the first argument. Now I want to pass all other arguments as arguments to the script sourced. When I pass parameters, everything is as I expect it. But when I don't pass parameters, the parameters from my outer script are taken instead.

Suppose I have the following two scripts:

outer.sh

#!/bin/bash

echo ${@}
MYARGS=${@:2}
echo $MYARGS 

. inner.sh $MYARGS

inner.sh

echo "inner arguments: $@"
echo "first: $1"

Results on the command line:

$ ./outer.sh one two #this is what I expected
one two
two
inner arguments: two
first: two

$ ./outer.sh one #this is what puzzles me
one

inner arguments: one
first: one

The result of the first invocation of my script is exactly what I expect, as I provided the parameter two. But the second invocation shows what I am trying to achieve: I don't any arguments passed to the script.

Is there any solution, which does not require me to change the values of the variables in my outer script?

Upvotes: 5

Views: 1260

Answers (2)

chepner
chepner

Reputation: 531185

Save the current set of arguments to be restored later, then modify the set before sourcing inner.sh.

#!/bin/bash

current_args=( "$@" )
set -- "${@:2}"   # Configure arguments for inner.sh
. inner.sh
set -- "${current_args[@]}"  # Restore arguments for outer.sh

Upvotes: 5

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

No. When you source a script the lines in the script are read and executed in the current interpreter. This means that it affects and is affected by the current execution environment including but not limited to variables, functions, options, and traps.

Upvotes: 1

Related Questions