BASH: difference between “export k=1” vs. “k=1”

2020-05-20 05:13发布

问题:

I am going to write an script and It looks there is no difference between:

export k=1

and

k=1

Am I right?

回答1:

Every process, even on Windows, has a block of memory known as the environment block, this contains environment variables. When a new process is created, by default, the environment block of the parent process is copied to the child, so environment variables are a simple way of passing text data to a child process.

The export command creates an environment variable, or converts an ordinary local variable into an environment variable. In the C-shell, one of its few redeeming features is that it uses a different syntax for environment variables (setenv) to local variables (set). Bourne shell derivatives, like Bash and Korn shell, hide all that.

Currently, only simple values can be passed, so items like arrays are not supported (it just exports the first element). Variable attributes, set using define, are also not exported unless the child process is a shell of the same type, i.e. another instance of bash. This also applies to exported functions, although it is possible to sometimes hack this between shells of different types (using eval).

In Bash (and others) there is a shell setting called allexport which means all variables are environment variables - probably a bad idea to se generally. You can supply a different environemnt block from languages like C using execve, but from the shell you need a program like env, see man env for details.



回答2:

export makes the variable available to subprocesses.

That is, if you spawn a new process from your script, the variable k won't be available to that subprocess unless you export it. Note that if you change this variable in the subprocess that change won't be visible in the parent process.

See section 3.2.3 of this doc for more detail.



回答3:

I've created a simple script to show the difference:

$ cat script.sh 
echo $answer

Let's test without export

$ answer=42
$ ./script.sh 

$ . script.sh 
42

The value is known only if using the same process to execute the script (that is, the same bash instance, using source / .)

Now, using export:

$ export answer=42
$ ./script.sh 
42
$ . script.sh 
42

The value is known to the subprocess.

Thus, if you want the value of a variable to be known by subprocesses then you should use export.



标签: linux bash shell