# Scope of environment variables in shells and shell scripts

A environment variable defined in a shell (or a shell script) stays defined everywhere, including inside new shells (or shell scripts) executed within the shell, until the shell (or the shell script) terminates or the variable gets unset explicitly. E.g.

script1.sh contains:

```
<br></br>export VAR1=testing<br></br>bash script2.sh<br></br>
```

script2.sh contains:

```
<br></br>echo $VAR1<br></br>
```

Then executing script1.sh gives the following:

```
<br></br>bash-3.00$ bash script1.sh <br></br>testing<br></br>bash-3.00$ echo $VAR1<p>bash-3.00$ echo $UNDEFINED_VAR</p><p>bash-3.00$ <br></br></p>
```

If a parent script defines a variable and then a child script redefines it, the child sees the new value but the parent retains the old value. E.g.

script1.sh contains:

```
<br></br>export VAR1=testing<br></br>bash script2.sh<br></br>echo $VAR1<br></br>
```

script2.sh contains:

```
<br></br>VAR1=overwritten<br></br>echo $VAR1<br></br>
```

Then executing script1.sh gives the following:

```
<br></br>bash-3.00$ bash script1.sh <br></br>overwritten<br></br>testing<br></br>bash-3.00$ <br></br>
```