Results 1 to 6 of 6
Is it possible to pass arguments to a source file in a bash script? For example
#!/bin/sh
#
. /dir1/dir1/funclib -a -b
How would you check for the passed arguments ...
- 04-24-2010 #1Just Joined!
- Join Date
- Nov 2008
- Posts
- 9
Passing arguments to a bash source file
Is it possible to pass arguments to a source file in a bash script? For example
#!/bin/sh
#
. /dir1/dir1/funclib -a -b
How would you check for the passed arguments in funclib without getting confused with any arguments passed to the main script?
Thanks
Don
- 04-24-2010 #2Linux User
- Join Date
- Nov 2009
- Location
- France
- Posts
- 292
There does not seem to be any confusion, both scripts process their arguments independantly. Can you elaborate more on expected or observed problems ?
0 + 1 = 1 != 2 <> 3 != 4 ...
Until the camel can pass though the eye of the needle.
- 04-24-2010 #3
Within a script, you can check the $1, $2, etc. variables for the arguments to the script.
These variables are parsed independently for each script. As an example:
Code:alex@danu:~/test/bash$ cat main_script.sh #!/bin/bash echo "main_script.sh: First argument: $1" source source_script.sh bar alex@danu:~/test/bash$ cat source_script.sh #!/bin/bash echo "source_script.sh: First argument: $1" alex@danu:~/test/bash$ bash main_script.sh foo main_script.sh: First argument: foo source_script.sh: First argument: bar
DISTRO=Arch
Registered Linux User #388732
- 04-24-2010 #4Just Joined!
- Join Date
- Nov 2008
- Posts
- 9
I created two test scripts - main.sh and mainsrc.sh. Here they are.
main.sh
mainsrc.shCode:#!/bin/sh # main.sh . ./mainsrc.sh -x -y -z while getopts :abc opt do case "$opt" in *) echo "main: ${opt}" ;; esac done
when I run main.sh -a -b -c I get the following output.Code:#!/bin/sh # mainsrc.sh while getopts :abcxyz opt do case "$opt" in *) echo "mainsrc: ${opt}" ;; esac done
[~] # ./main.sh -a -b -c
mainsrc: x
mainsrc: y
mainsrc: z
If I changed main.sh to the following:
I get the following output when I run it:Code:#!/bin/sh # main.sh while getopts :abc opt do case "$opt" in *) echo "main: ${opt}" ;; esac done . ./mainsrc.sh -x -y -z
[~] # ./main.sh -a -b -c
main: a
main: b
main: c
So as you can see they are interferring with each other. How to solve this?
Don
- 04-25-2010 #5Linux User
- Join Date
- Nov 2009
- Location
- France
- Posts
- 292
From BASH man page
AddingThe shell does not reset OPTIND automatically; it must be manually reset between multiple calls to getopts within the same shell invocation if a new set of parameters is to be used.after every getopts full completion resolved the issue. So the problem lies in the way getopts is built.Code:OPTIND=1
0 + 1 = 1 != 2 <> 3 != 4 ...
Until the camel can pass though the eye of the needle.
- 04-25-2010 #6Just Joined!
- Join Date
- Nov 2008
- Posts
- 9
Excellent! So simple. It solves the problem. Thanks.


Reply With Quote