Sample Header Ad - 728x90

pass all parameters to another sourced bash script that uses getopts

-1 votes
1 answer
268 views
I am trying to pass all parameters from one script to another. However, there is an issue when the other script is sourced; all parameters are not passing correctly. **first.sh:**
#!/usr/bin/bash


while getopts a option 
do 
    case "${option}"
    in
    a) echo 'OptionA:somevalue';; 
    esac 
done

# This way works
./second.sh "$@"

# Does not work when source command is used
#source ./second.sh "$@"
**second.sh:**
#!/usr/bin/bash


while getopts b:c option 
do 
    case "${option}"
    in
    b) echo 'OptionB:'"${OPTARG}";; 
    c) echo 'OptionC:somevalue';;
    esac 
done
**Output:**
$ ./test.sh -a -b foo -c
OptionA:somevalue
./first.sh: illegal option -- b
./second.sh: illegal option -- a
OptionB:foo
OptionC:somevalue
**Expected output:**
$ ./test.sh -a -b foo -c
OptionA:somevalue
OptionB:foo
OptionC:somevalue
**What to achieve?** Passing the parameters correctly to second.sh with source command, getting rid of illegal option and compatibility with other shells. Edit: Updated the question again with more clear examples.
Asked by Zero (39 rep)
Mar 9, 2024, 03:58 PM
Last activity: Mar 20, 2024, 08:44 AM