0

So basically was wondering if I can just get the variables defined before the shell script command?

$ FOO=bar myscript.sh

or

$ myscript.sh FOO=bar

And within the myscript.sh just get FOO similar to how you can get arguments.

Thank you in advanced!

nowk
  • 32,822
  • 2
  • 35
  • 40

1 Answers1

1
$ 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.)

rici
  • 234,347
  • 28
  • 237
  • 341