In my Bash script, I have a global variable foo set to some value and a function process back_func that is run in the background. I would like the background process to be able to access foo and modify its value, so that the change can be seen by the main process.
My script is structured in the following way:
#!/bin/bash
foo=0
function back_func {
foo=$(($foo+1))
echo "back $foo"
}
(back_func) &
echo "global $foo"
The output of the above script is
global 0
back 1
How can I get the global and back lines to both end with 1? In other words, how can I make background process’s modification of foo be picked up by the main process?
Upgrade 2019
Playing with
bash_ipc_demoadding 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
getMyGlobalVarfunctionwill require
--syncflag 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_demoin 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 640×220 PNG graphic, with
uptime_graph_valvalues.In this case, as
back_func startwas invoked with-g 3600from morethan one hour, graphic show 3600 peek on 640 columns and 0-100% on 220 lines:
(Nota: Command was originaly named
lastMinuteGraphas 1st version of this just stored 60 values, now this useuptime_graph_valfor number of values to store. As I’ve used-g 3600argument, this command could by namedlastHourGraph).Then: