The existence of the local and declare builtin commands may render it counter-intuitive that the wanted functionality is actually available from the export builtin, at least on Bash.
According to the Bash manual, the export command has an -n option, which "causes the export property to be removed from each name". This also applies while declaring variables with values right ahead.
The following snippet demonstrates the usage:
VAR=old-value function func () { export -n "$1=$2" } func VAR new-value echo "VAR=$VAR" # prints VAR=new-value
One may create one own's global function, and use it inside other functions:
VAR=old-value function global () { export -n "$1=$2" } function main () { global VAR "$1" } main main-value echo "VAR=$VAR" # prints VAR=main-value
This is verified working on
- an old Bash 2.03.0(1) running on a (modern) OS/390 z/OS
- on a Bash 3.2.57(1) on macOS 10.15
- on a Bash 4.1.2(2) on CentOS 6
I used this to inspect the various possibilities:
#!env bash export LANG=C LC_ALL=C A=a0 B=b0 C=c0 D=d0 E=e0 export F=f0 function testfunc () { local "$1=$2" ; shift 2 declare "$1=$2" ; shift 2 declare -g "$1=$2" ; shift 2 export -n "$1=$2" ; shift 2 export "$1=$2" } echo "$A/$B/$C/$D/$E" testfunc A a1 B b1 C c1 D d1 E e1 echo "$A/$B/$C/$D/$E" export -p | grep -E '^declare -x [ABCDEF]='
In case of macOS 10.15 this shows an output similar to this:
$ bash test.sh a0/b0/c0/d0/e0 test.sh: line 15: declare: -g: invalid option declare: usage: declare [-afFirtx] [-p] [name[=value] ...] a0/b0/c0/d1/e1 declare -x E="e1" declare -x F="f0"
The output shows that the local and declare commands used in the testfunc function effectively do not apply the variables in the global context (as documented) and that the declare -g option is not widely supported yet. It also shows that the variables D and E have been changed in the global context from inside the testfunc function (as hoped for), while only the E variable has been marked for export as a side effect by the export command, showing that the export -n option is effective. The variable F is there just to verify the grep command worked as expected.
eval.script --arg1=valautomatically creates variable named arg1 with value val ermmm... can't you just run this likearg1=val scriptand it will be set for the duration of running the script?