How to make a pipe loop in bash

前端 未结 7 1510
半阙折子戏
半阙折子戏 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:53

    A command stack can be composed as string from an array of arbitrary commands and evaluated with eval. The following example gives the result 65536.

    function square ()
    {
      read n
      echo $((n*n))
    }    # ----------  end of function square  ----------
    
    declare -a  commands=( 'echo 4' 'square' 'square' 'square' )
    
    #-------------------------------------------------------------------------------
    #   build the command stack using pipes
    #-------------------------------------------------------------------------------
    declare     stack=${commands[0]}
    
    for (( COUNTER=1; COUNTER<${#commands[@]}; COUNTER++ )); do
      stack="${stack} | ${commands[${COUNTER}]}"
    done
    
    #-------------------------------------------------------------------------------
    #   run the command stack
    #-------------------------------------------------------------------------------
    eval "$stack" 
    
    0 讨论(0)
提交回复
热议问题