Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shell command to delay a buffer?

Tags:

bash

shell

I am looking for a shell command X such as, when I execute:

command_a | X 5000 | command_b

the stdout of command_a is written in stdin of command_b (at least) 5 seconds later.

A kind of delaying buffer.

As far as I know, buffer/mbuffer can write at constant rate (a fixed number of bytes per second). Instead, I would like a constant delay in time (t=0 is when X read a command_a output chunk, at t=5000 it must write this chunk to command_b).

[edit] I've implemented it: https://github.com/rom1v/delay

like image 477
rom1v Avatar asked Jan 07 '14 19:01

rom1v


People also ask

How do I delay in bash?

It is as easy as typing sleep N . This will pause your script for N seconds, with N being either a positive integer or a floating point number. Consider this basic example: echo "Hello there!" sleep 2 echo "Oops!

How do you pause in shell?

There is no pause command under Linux/UNIX bash shell. You can easily use the read command with the -p option to display pause along with a message.

What is wait in shell script?

wait is an inbuilt command in the Linux shell. It waits for the process to change its state i.e. it waits for any running process to complete and returns the exit status.


2 Answers

As it seemed such a command dit not exist, I implemented it in C: https://github.com/rom1v/delay

delay [-b <dtbufsize>] <delay>
like image 71
rom1v Avatar answered Nov 02 '22 17:11

rom1v


This might work

time_buffered () {
   delay=$1
   while read line; do
       printf "%d %s\n" "$(date +%s)" "$line"
   done | while read ts line; do
       now=$(date +%s)
       if (( now - ts < delay)); then
           sleep $(( now - ts ))
       fi
       printf "%s\n" "$line"
   done
}

commandA | time_buffered 5 | commandB

The first loop tags each line of its input with a timestamp and immediately feeds it to the second loop. The second loop checks the timestamp of each line, and will sleep if necessary until $delay seconds after it was first read before outputting the line.

like image 23
chepner Avatar answered Nov 02 '22 17:11

chepner