I have noticed some weird behavior when sourcing another script within my shell script. The script that I am sourcing to setup the environment in my shell script takes an optional argument, e.g.
source setup.sh version1
However in my shell script I have also have command line argument variables. For example:
./myscript.sh TEST 1
Inside myscript.sh:
#!/bin/zsh
source setup.sh
echo ROOT version setup $ROOT_SYS
...more of the script
The problem that I have noticed with my script above is that the $1 argument (TEST in this example) is used in the source setup.sh command. This causes the command to become
source setup.sh TEST
which of course fails as setup.sh does not have a version TEST.
I solved this problem by editing my script to below.
#!/bin/zsh
source setup.sh version1
echo ROOT version setup $ROOT_SYS
...more of the script
The source command now does not pick up the $1 argument.
Why/How does the source command pick up the $1 argument when I am running my shell script?
This is because source executes the code of
setup.shas if it was in place, so whensetup.shaccess, say,$1, the value it has is that of the first argument of the actual script. If you want to avoid that you could either execute it:or, if you need to get back some variables or values from it, change it to return the result in form of an output, something like:
Finally, as you figured out, the
sourcekeywords also allows providing arguments to the scripts, but it bypasses current arguments if you don’t provide any.