Defining a variable with or without export

后端 未结 14 1487
借酒劲吻你
借酒劲吻你 2020-11-22 09:58

What is export for?

What is the difference between:

export name=value

and

name=value
14条回答
  •  孤街浪徒
    2020-11-22 10:55

    As you might already know, UNIX allows processes to have a set of environment variables, which are key/value pairs, both key and value being strings. Operating system is responsible for keeping these pairs for each process separately.

    Program can access its environment variables through this UNIX API:

    • char *getenv(const char *name);
    • int setenv(const char *name, const char *value, int override);
    • int unsetenv(const char *name);

    Processes also inherit environment variables from parent processes. Operating system is responsible for creating a copy of all "envars" at the moment the child process is created.

    Bash, among other shells, is capable of setting its environment variables on user request. This is what export exists for.

    export is a Bash command to set environment variable for Bash. All variables set with this command would be inherited by all processes that this Bash would create.

    More on Environment in Bash

    Another kind of variable in Bash is internal variable. Since Bash is not just interactive shell, it is in fact a script interpreter, as any other interpreter (e.g. Python) it is capable of keeping its own set of variables. It should be mentioned that Bash (unlike Python) supports only string variables.

    Notation for defining Bash variables is name=value. These variables stay inside Bash and have nothing to do with environment variables kept by operating system.

    More on Shell Parameters (including variables)

    Also worth noting that, according to Bash reference manual:

    The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described in Shell Parameters. These assignment statements affect only the environment seen by that command.


    To sum things up:

    • export is used to set environment variable in operating system. This variable will be available to all child processes created by current Bash process ever after.
    • Bash variable notation (name=value) is used to set local variables available only to current process of bash
    • Bash variable notation prefixing another command creates environment variable only for scope of that command.

提交回复
热议问题