Shell – Implement Circular Flow of Data Among Commands

command linepipescriptingshell

I know of two types how commands can be connected with each other:

  1. by using a Pipe (putting std-output into std-input of the next
    command).
  2. by using a Tee (splice the output into many outputs).

I do not know if that is all that is possible,
so I draw a hypothetical connection type:

enter image description here

How could it be possible to implement a circular flow of data among commands like for instance in this pseudo code, where I use variables instead of commands.:

pseudo-code:

a = 1    # start condition 

repeat 
{
b = tripple(a)
c = sin(b) 
a = c + 1 
}

Best Answer

Circular I/O Loop Implemented with tail -f

This implements a circular I/O loop:

$ echo 1 >file
$ tail -f file | while read n; do echo $((n+1)); sleep 1; done | tee -a file
2
3
4
5
6
7
[..snip...]

This implements the circular input/output loop using the sine algorithm that you mentioned:

$ echo 1 >file
$ tail -f file | while read n; do echo "1+s(3*$n)" | bc -l; sleep 1; done | tee -a file
1.14112000805986722210
.72194624281527439351
1.82812473159858353270
.28347272185896349481
1.75155632167982146959
[..snip...]

Here, bc does the floating point math and s(...) is bc's notation for the sine function.

Implementation of the Same Algorithm Using a Variable Instead

For this particular math example, the circular I/O approach is not needed. One could simply update a variable:

$ n=1; while true; do n=$(echo "1+s(3*$n)" | bc -l); echo $n; sleep 1; done
1.14112000805986722210
.72194624281527439351
1.82812473159858353270
.28347272185896349481
[..snip...]
Related Question