Bash. What’s export for?

Asked

Viewed 200 times

4

Looking at Bash scripts, I realized that variables can be created in the following ways:

script1.sh:

variable1=Ola
export variable2="Ola de novo"

Find out more about the difference between these two ways of declaring variables. And from what I understand export would serve to make global variables. But by running the script and trying to print the global variable variable2, I get the same result as the local variable in my script ``variable1````

$ ./script1.sh 
$ echo $variable1
$
$ echo $variable2
$

Using the command source or using . And by performing the same procedure above, you get as a result the printing of the two variables.

$ source script1.sh 
$ echo $variable1
Ola
$ echo $variable2
Ola de novo

At this point I understood that the objective of export is not to declare global variables. What is the purpose of the export command?

  • This question may help you: https://stackoverflow.com/questions/1158091/defining-a-variable-with-or-without-export

1 answer

3

When you set a variable using export, this variable is copied to the shell children when it does fork. Without the export, the variable is not copied to the children.

When you call ./script1.sh, the shell makes a fork and the script runs in the child process, not in the shell where you called the command. Therefore, the definition of variables is done in the child process, and not in the shell where you are logged in. That’s why you can’t give echo in the parent process variables. The child process does not touch the parent process Nvironment.

The program source is a program that is built-in in the shell itself, and serves to execute a script in the shell itself, without doing fork. That’s why when you call source script1.sh, variables appear in the shell where you are logged in.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.