Reputation: 934
i am just wondering is there anyway to source a file and then down in track source the file again?
I am using https://github.com/renatosilva/easyoptions on my bash script, i am sourcing easyoption.sh on the main script and which works fine. but when i have other scripts which gets loaded later on from the main script, i want easyoptions.sh to be sourced and --help should work on the last loaded file.
example:
test.sh
#!/bin/bash
## EasyOptions Sub Test
## Copyright (C) Someone
## Licensed under XYZ
## -h, --help All client scripts have this, it can be omitted.
script_dir=$(dirname "$BASH_SOURCE")
# source "${script_dir}/../easyoptions" || exit # Ruby implementation
source "${script_dir}/easyoptions.sh" || exit # Bash implementation, slower
main.sh
#!/bin/bash
## EasyOptions Main
## Copyright (C) Someone
## Licensed under XYZ
## Options:
## -h, --help All client scripts have this, it can be omitted.
## --test This loads test.sh.
script_dir=$(dirname "$BASH_SOURCE")
# source "${script_dir}/../easyoptions" || exit # Ruby implementation
source "${script_dir}/easyoptions.sh" || exit # Bash implementation, slower
if [[ -n "$test" ]];then
source "${script_dir}/test.sh"
fi
Now when i try ./main.sh --help it displays
EasyOptions Main
Copyright (C) Someone
Licensed under XYZ
Options:
-h, --help All client scripts have this, it can be omitted.
> --test This loads test.sh.
Now i want below to work ./main.sh --test --help and it should output
EasyOptions Sub Test
Copyright (C) Someone
Licensed under XYZ
-h, --help All client scripts have this, it can be omitted.
But instead it always displays main.sh help
Upvotes: 1
Views: 512
Reputation: 351
as @pynexj said, "when you source easyoptions.sh it will parse all the command line options " so you need following steps:
1.you need to check arguments in main process:
1.1 if the 1st argument is --help(1st argument means $1,not $0 "file name"),then show main help,
1.2 if the 1st argument is --test, loads test.sh and pass other arguments to child.
here is an simple example, passing main.sh's argument to child(proc.sh).
main.sh:
echo "main:"
echo $1
echo $2
source ./proc.sh $2
proc.sh:
echo "proc:"
echo $1
when you run cmd
./main.sh test help
output:
main:
test
help
proc:
help
you can see,the second argument of main.sh is passed to child
Upvotes: 1
Reputation: 20797
In main.sh
when you source easyoptions.sh
it will parse all the command line options (including both --help
and --test
). Later when you source test.sh
the easyoptions would have nothing to parse (i.e. it would not see --help
). You can verify this by adding echo "$@"
before source test.sh
.
Upvotes: 1