Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

export not working in my shell script

I have two scripts 1.sh and 2.sh.

1.sh is as follows:

#!/bin/sh
variable="thisisit"
export variable

2.sh is as follows:

#!/bin/sh
echo $variable

According to what I read, doing like this (export) can access the variables in one shell script from another. But this is not working in my scripts. Can somebody please help. Thanks in advance.

like image 237
Xander Avatar asked May 28 '12 08:05

Xander


People also ask

How do you export from shell?

You can use the export command to make local variables global. To make your local shell variables global automatically, export them in your . profile file. Note: Variables can be exported down to child shells but not exported up to parent shells.

How does export work bash?

Export is a command used in the bash shell to make use of variables and functions that are to be passed on further to all child processes. It works by including a variable in child process environments. This is done by keeping another environment.

What does $() mean in shell script?

$() – the command substitution. ${} – the parameter substitution/variable expansion.

What is the command for export?

To display all the exported environment variable of the current shell, execute the command with -p option as follows: export -p.


2 Answers

If you are executing your files like sh 1.sh or ./1.sh Then you are executing it in a sub-shell.

If you want the changes to be made in your current shell, you could do:

. 1.sh
# OR
source 1.sh

Please consider going through the reference-documentation.

"When a script is run using source [or .] it runs within the existing shell, any variables created or modified by the script will remain available after the script completes. In contrast if the script is run just as filename, then a separate subshell (with a completely separate set of variables) would be spawned to run the script."

like image 107
linuxeasy Avatar answered Sep 22 '22 09:09

linuxeasy


export puts a variable in the executing shell's environment so it is passed to processes executed by the script, but not to the process calling the script or any other processes. Try executing

#!/bin/sh
FOO=bar
env | grep '^FOO='

and

#!/bin/sh
FOO=bar
export FOO
env | grep '^FOO='

to see the effect of export.

To get the variable from 1.sh to 2.sh, either call 2.sh from 1.sh, or import 1.sh in 2.sh:

#!/bin/sh
. ./1.sh
echo $variable
like image 37
Fred Foo Avatar answered Sep 21 '22 09:09

Fred Foo