4

I'm trying to achieve this

while condition; do

var=value1

### update value every 5s
while sleep 5; do
var=value2
done
### 

 ...
[ rest of code ]

done

The problem here is that the script will always enter the loop and block the rest of the code

  • 1
    Do you want to keep the [rest of code] running concurrently with the inner loop? – Quasímodo May 02 '20 at 16:49
  • yeah in parallel – Belka h.j May 02 '20 at 16:58
  • change inner loop to sleep 5 && var=value2, but what is the usecase of this job? – αғsнιη May 02 '20 at 17:00
  • 3
    https://unix.stackexchange.com/a/225364/108618 – Kamil Maciorowski May 02 '20 at 17:33
  • Please write a title that better reflects your question. – Quasímodo May 02 '20 at 17:44
  • 1
    Are you intending the loop to run in the background, updating the value of $val, and have the rest of the code be able to see those updated values? If so (and also if your intention is something else), this should be made clearer in the question. – Kusalananda May 02 '20 at 18:22
  • 1
    bash doesn't provide any primitives for parallel operations besides job control. It doesn't have threading or async built in. Any parallel operation has to be done as a separate process. I think you're trying to fit a square peg in a round hole, but my suggestion would be to set up two completely different processes that share data via an actual file. – kojiro May 03 '20 at 15:39

1 Answers1

2

one thing to try in order to achieve a degree of asynchronous setting of a variable is:

#!/usr/bin/env bash

async() {
  while :; do
    # send SIGUSR1 to "parent" script
    kill -USR1 "$1"
    sleep 1
  done
}

# provide PID of script to async
async $$ &
async_pid=$!

declare -i i=0
update() {
  i=42
}

cleanup() {
  kill ${async_pid}
}

trap update USR1
trap cleanup EXIT

echo $i
sleep 2
echo $i

One caveat with this approach is: if the script is sleeping and the signal is raised, the update command is only executed once when the script is "awake" again.

noAnton
  • 361