$ FOO=bar myscript.sh
is handled by the shell, which creates a new environment to run myscript.sh
and adds FOO=bar
to that environment. Environment variables do not contain any contextual information; an environment variable is just an environment variable. It is not possible for myscript.sh
to distinguish between the above command and the sequence:
export FOO=bar
# ...
myscript.sh
regardless of how many commands were omitted by the ellipsis.
In contrast,
myscript.sh FOO=bar
simply passes a command line option to myscript.sh
, which will see FOO=bar
as the value of $1
. It's relatively easy to parse the positional arguments to find arguments which have the form of an assignment, although some care must be taken to avoid false positives. (I.e., it is not enough to just use all positional parameters which contain an =
character; a check should be made that the preceding characters are all valid identifier characters.)