The shell variable is created by a script. It needs to be retained even after closing terminal and launching another script and accessing it.

I don't want to write to a file(in HDD). If it possible to write the content of variable in file(that is stored exclusively in RAM), how can it be done?

The data needs to be changed frequently, so I don't want to do so much I/O operations to Hard disk.

  • If your data changes frequently (to the point where your are concerned about the I/O operations for performances), then storing it in an "enhanced" environment variable is probably not a good solution: the value may change during your shells life. Meanwhile, if you still want to go that route and store the data in memory, you can create a tmpfs device, mount it and use it as a regular HDD to store a file with the value. – Zeitounator Apr 9 '19 at 6:37
  • You could also look into tmpfs, a filesystem that exists in-memory and backed by swap space. – Haxiel Apr 9 '19 at 9:59

To survive reboots and close of terminal you need to write the variable value in file. You can write it on this way (for example)

echo "$VAR" >/path/to/file

You can restore it on this way (for example)

VAR="`cat /path/to/file`"

And you need to store it in file on every change of value

| improve this answer | |

A variable set in one environment cannot be accessed in parent or other (non-child) shells. The following will work:

export my_variable="testing..."
echo $my_variable

But $my_variable will not be accessible in another terminal, unless you put these lines in some file (e.g. .bashrc or a file executable by .bashrc)

Another option is to use fish shell...

fish -c "set -u my_variable 'testing...'"

You can read more here

From the fish documentation

-U or --universal causes the specified shell variable to be given a universal scope. If this option is supplied, the variable will be shared between all the current user's fish instances on the current computer, and will be preserved across restarts of the shell.

Not sure what exactly is your requirement, but just out of curiosity: if you are concerned about the contents of the variable being accessible / readable, you can write the data to a file and set the permissions to --x------ and put the file in .bashrc.

| improve this answer | |
  • I think your fish example needs a bit more explanation as it's not clear how that would help. – Kusalananda Apr 9 '19 at 6:47

1) Get/Generate some C/Shell code/program to echo/cout it's PID.

2) Name that file, call it "whatever" and compile/chmod +x "whatever"

3) ./allocate $("./whatever --name='$(plugin)' ")

And that should do it.

[P.S] This needs to reference its own self in memory. It is possible, break out of the shell

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.