3

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

7
  • 1
    Do you want to keep the [rest of code] running concurrently with the inner loop?
    – Quasímodo
    May 2 '20 at 16:49
  • yeah in parallel
    – Belka h.j
    May 2 '20 at 16:58
  • 3
  • 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 2 '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 3 '20 at 15:39
1

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.

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.