Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH: difference between "export k=1" vs. "k=1"

Tags:

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

export k=1 

and

k=1 

Am I right?

like image 919
lashgar Avatar asked Sep 24 '12 08:09

lashgar


People also ask

What does export mean Bash?

Export is a built-in command of the Bash shell. It is used to mark variables and functions to be passed to child processes. Basically, a variable will be included in child process environments without affecting other environments.

What is the difference between export and set in Linux?

See help set : set is used to set shell attributes and positional attributes. Variables that are not exported are not inherited by child processes. export is used to mark a variable for export.

What is set in Bash?

The set command in Bash allows you to control the behavior of your scripts by managing specific flags and properties. These safeguards guarantee that your scripts are on the right track and that Bash's odd behavior does not cause problems.


2 Answers

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.

like image 178
Brian Agnew Avatar answered Oct 04 '22 02:10

Brian Agnew


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.

like image 27
Mihai Maruseac Avatar answered Oct 04 '22 04:10

Mihai Maruseac