How do you export a variable through shell script?

Answering my own question here, using the answers above: if I have more than one related variable to export which use the same value as part of each export, I can do this:

#!/bin/bash
export TEST_EXPORT=$1
export TEST_EXPORT_2=$1_2
export TEST_EXPORT_TWICE=$1_$1

and save as e.g. ~/Desktop/TEST_EXPORTING

and finally $chmod +x ~/Desktop/TEST_EXPORTING

--

After that, running it with source ~/Desktop/TEST_EXPORTING bob

and then checking with export | grep bob should show what you expect.


You can put export statements in a shell script and then use the 'source' command to execute it in the current process:

source a.sh

I hope this helps.


Exporting a variable into the environment only makes that variable visible to child processes. There is no way for a child to modify the environment of its parent.


You can't do an export through a shell script, because a shell script runs in a child shell process, and only children of the child shell would inherit the export.

The reason for using source is to have the current shell execute the commands

It's very common to place export commands in a file such as .bashrc which a bash will source on startup (or similar files for other shells)

Another idea is that you could create a shell script which generates an export command as it's output:

shell$ cat > script.sh
#!/bin/sh
echo export foo=bar
^D
chmod u+x script.sh

And then have the current shell execute that output

shell$ `./script.sh`

shell$ echo $foo
bar

shell$ /bin/sh
$ echo $foo
bar

(note above that the invocation of the script is surrounded by backticks, to cause the shell to execute the output of the script)

Tags:

Shell

Ubuntu