0

We have an issue that I am able to recreate with this simple example. I have the following sample shell script file, named SO-shell.txt

#!/bin/bash
export my_var="A quick bown fox"
echo my_var was set to "$my_var"

When I run SO-shell.txt I get the following output:
my_var was set to A quick bown fox

After the script has finished execution, if I execute the following at the shell command line:
shell> echo "$my_var"

I don't see anything (i.e. shell variable did not get assigned beyond the lifespan of the shell script)


Q) How to make a shell variable outlive the lifespan of its defining shell script?

Sandeep
  • 1,245
  • 1
  • 13
  • 33
  • 1
    You can't. Nor would you want to. Perhaps you want to source the file rather than execute it. – William Pursell Dec 03 '20 at 18:24
  • Possible duplicate questions: ["Can I export a variable to the environment from a bash script without sourcing it?"](https://stackoverflow.com/questions/16618071/can-i-export-a-variable-to-the-environment-from-a-bash-script-without-sourcing-i), ["bash forgets export variable"](https://stackoverflow.com/questions/10457725/bash-forgets-export-variable), and ["How to export a variable in bash"](https://stackoverflow.com/questions/307120/how-to-export-a-variable-in-bash). – Gordon Davisson Dec 03 '20 at 18:30

2 Answers2

1

The export and ‘declare -x’ commands allow parameters and functions to be added to and deleted from the environment.

Bash Reference Manual - Environment

By using export command, basically you are declaring the variable for this specific process and its child-processes.

However, as workaround you can execute your script in the next way . SO-shell.tx

As example:

[19:30:50][/]# bash test.sh
my_var was set to A quick bown fox
[19:30:59][/]# echo $my_var

[19:31:11][/]# . test.sh
my_var was set to A quick bown fox
[19:31:15][/]# echo $my_var
A quick bown fox

You have more information about this here: Export variable from bash script

vsergi
  • 705
  • 1
  • 6
  • 16
0

How to make a shell variable outlive the lifespan of its defining shell script?

It's impossible (in normal shell implementations). Because shell variables are stored in memory inside the shell process and after a process dies all process memory is returned to the operating system, all information stored there is lost including the variable.

You can basically use any method of interprocess communication:

  • Use a file.
    • Store the variable value to a file from child shell and restore it in parent shell.
    • Store the variable definition (ie. declare -p my_var) in the file in child shell and source the file in parent shell.
  • Output the variable and grab the output in parent shell with command substitution.
  • Use a fifo between child and parent shell
  • Write your own tooling or your own shell implementation that would for example use shared memory to store the variable.
KamilCuk
  • 120,984
  • 8
  • 59
  • 111