How to make a pipe loop in bash

前端 未结 7 1562
半阙折子戏
半阙折子戏 2020-12-05 03:25

Assume that I have programs P0, P1, ...P(n-1) for some n > 0. How can I easily redirect the output of program Pi

7条回答
  •  一个人的身影
    2020-12-05 03:38

    My solutions uses pipexec (Most of the function implementation comes from your answer):

    square.sh

    function square() {
      # square numbers
    
      read j                         # receive first "request"
      while [ "$j" != "" ]; do
        let jj=$j*$j
        echo "square($j) = $jj" >&2  # debug message
    
        echo $jj                     # send square
    
        read j                       # receive next "request"
      done
    }
    
    square $@
    

    calc.sh

    function calc() {
      # calculate sum of squares of numbers 0,..,10
    
      sum=0
      for ((i=0; i<10; i++)); do
        echo $i                   # "request" the square of i
    
        read ii                   # read the square of i
        echo "got $ii" >&2          # debug message
    
        let sum=$sum+$ii
     done
    
     echo "sum $sum" >&2           # output result to stderr
    }
    
    calc $@
    

    The command

    pipexec [ CALC /bin/bash calc.sh ] [ SQUARE /bin/bash square.sh ] \
        "{CALC:1>SQUARE:0}" "{SQUARE:1>CALC:0}"
    

    The output (same as in your answer)

    square(0) = 0
    got 0
    square(1) = 1
    got 1
    square(2) = 4
    got 4
    square(3) = 9
    got 9
    square(4) = 16
    got 16
    square(5) = 25
    got 25
    square(6) = 36
    got 36
    square(7) = 49
    got 49
    square(8) = 64
    got 64
    square(9) = 81
    got 81
    sum 285
    

    Comment: pipexec was designed to start processes and build arbitrary pipes in between. Because bash functions cannot be handled as processes, there is the need to have the functions in separate files and use a separate bash.

提交回复
热议问题