pure-bash-bible icon indicating copy to clipboard operation
pure-bash-bible copied to clipboard

Using coproc with read in non-interactive shells for sleep alternative

Open andryyy opened this issue 3 years ago • 0 comments

Hi,

First of all: THANK YOU! So glad I found this.

I noticed I run in a lot of defunct procs when using the sleep alternative in your docs, I don't know why yet, though.

As an alternative I found it useful to use coproc to give the sub process a stdin:

delay() {
  declare -i i=$1
  coproc d {
    read -n1 -s -t$i
  }
  wait $!
}

This can be modified to be used in a creative way!

In this example I spawn a 30s delay and, while it is already counting down, do some other things in the meantime that are not related to the delay. When I'm done doing things, I will wait for the remaining delay time:

delay() {
  declare -i i=$1
  coproc d {
    read -n1 -s -t$i
  }
}

delay 30
while [ -v d ]; do
  echo "Doing things"
  wait
done

You'd also be able to stop the delay prematurely by sending input to the pipe: echo > /dev/fd/${d[1]}

André

andryyy avatar Jan 31 '23 08:01 andryyy