vasu aluvosu vasu aluvosu - 3 months ago 21
Bash Question

Bash Restrict parent script command line arguments carry forward to child scripts arguments

We have parent bash script

parent_source.bash

#!/bin/bash

source child_test.bash


Inside the child_test.bash

echo $@
#Doing some validation checks for $@, for child_script command line arguments are optional


Where as when executing

source parent_source.bash one two


The child script is taking "one" and "two" in the $@ so validation is failing, It is not considering as zero arguments given to child script. Child script assuming it got 2 command line arguments.

But if we give command line args for child also It is working fine.

Could Someone please help us

Thanks

Answer

When executing the source command, you actually injecting the content of child_test.bash to your parent_source.bash script, and then, when the first line in the child_test.bash is being executed, ie:

echo $@

It actually refers to the arguments passed to the parent script since the scope of the command is actually on the parent_source.bash script.

I suggest to execute the script without injecting the content to the parent script.

Something like this:

parent_source.bash:

#!/bin/bash

./child_test.bash

child_test.bash:

echo $@ 
#Doing some validation checks for $@, for child_script command line arguments are optional