Expanding on the answer from Wildcard, and after sourcing the file (with all the same caveats around only doing this only if you trust the file), we can identify exported variable names by scanning for them, get their declaration and re-export them.
source-export() {
local FILENAME=$1
shift
source <(
source "${FILENAME}" "$@"
# show the exported names
PATTERN="\b(?<=export)(\s+\w+)+"
while read -r NAME; do
[[ -n ${NAME} ]] && typeset -p "${NAME}"
done < <(grep -oP "${PATTERN}" "${FILENAME}" | tr ' ' '\n')
)
}
Note: the pattern we use to scan for exports should be reasonably robust (handling cases like export A B). Another potentially more robust approach would be to diff the variable table pre- and post-sourcing for exported variables.
Example:
$ cat foo.sh
export XXX="432"
YYY=111
export ZZZ="'adfa $*"
export A B
A=1
B=2
C=3
$ source-export foo.sh 3 2 1
$ echo -e "XXX=$XXX\nYYY=$YYY\nZZZ=$ZZZ\nA=$A\nB=$B\nC=$C"
XXX=432
YYY=
ZZZ='adfa 3 2 1
A=1
B=2
C=
versus:
$ source foo.sh 3 2 1
$ echo -e "XXX=$XXX\nYYY=$YYY\nZZZ=$ZZZ\nA=$A\nB=$B\nC=$C"
XXX=432
YYY=111
ZZZ='adfa 3 2 1
A=1
B=2
C=3
Tested on bash and zsh.