I have a global var foo="some value" and a background process back_func, I want to the background process to access $foo and modify its value, which can be seen by the main process. It's something like the following:
#!/bin/bash
foo=0
function back_func {
foo=$(($foo+1))
echo "back $foo"
}
(back_func) &
echo "global $foo"
The result of the above script is
global 0
back 1
How could I get the result of global and back are both '1'?, i.e. the back ground process's modification can return back to the main process.
If the main process (let's call it main.sh) is another periodically running bash script then you could simply have the the other script (let's call it other.sh) write the value to a file (let's call this file value.sh).
other.sh
main.sh
Upgrade 2019
Playing with
bash_ipc_demo
adding completion and a graph generator.Rendez-vous
If you wanna have two independant process which could communicate, you have to place a rendez-vous somewhere both process can reach.
This could be a simple file, a fifo pipe, a unix socket, a TCP socket or maybe else (Rexx port).
bash and other shell
Bash don't have a equivalent to rexx port, so there is a little sample, using a rendez-vous file, that work (on my Linux).
I'm using shared memory
/dev/shm
, to reduce disk load.Simple counter sample
Let play
Than stop now:
or
More than one variables
For having many vars, there could by a nice manner:
Then
and from there, why not:
or
Get variable with snapshot
and finally
getMyGlobalVar
functionwill require
--sync
flag for re-reading rendez-vous in order to let you look about each fields from the same snapshot.Full useable demo:
There is a full sample: bash_ipc_demo or bash_ipc_demo.shz
You could use by:
From there, if you
source bash_ipc_demo
in another terminal, you could do the list into them.You could even close the first terminal.
Then, you could get one value
or build a quick cpu graph:
This will render a 640x220 PNG graphic, with
uptime_graph_val
values. In this case, asback_func start
was invoked with-g 3600
from more than one hour, graphic show 3600 peek on 640 columns and 0-100% on 220 lines:(Nota: Command was originaly named
lastMinuteGraph
as 1st version of this just stored 60 values, now this useuptime_graph_val
for number of values to store. As I've used-g 3600
argument, this command could by namedlastHourGraph
).Then:
According to the Bash manual here,
And since a process run in a subshell cannot modify the environment of the parent shell, I guess what you are trying to do is only possible via temp files / named pipes. Or you could rethink your approach.