Don Omar
Don Omar

Reputation: 91

Bash Print n nunber of lines from the output of progressive loop

Case Scenario: My script contains a loop that produces x number of lines, and after each loop x increases may be doubled or tripled etc. I want to print n number of lines from the output but without any halt.

eg.

fun() { unset var res; var=$1; while true; do res=$(seq $var); printf "%s\n" $res; let var++; done; }
fun 1
Output:
1
1
2
1
2
3
1
2
3
4
1
2
3
4
5
.
.
.
Infinite Loop

Controlling above loop via

fun() { unset var res; var=$1; start=1; while true; do until [[ $start == $2 ]]; do res=$(seq $var); printf "%s\n" $res; let var++; let start++; done; if [[ $start == $2 ]]; then break; fi; done; }

fun 5 3 #only first 3 lines of fun 5 should be outputted Controlling the number of time loop is runned is not option; since as shown above after every loop output lines are increased; ( first time only 1; then 1 2; then 1 2 3...), so fun 5 3 will not print 3 line I want to print n number of lines from that output.

eg. fun 5 $max; #where $max is number of lines i wanted to print
Dont want to use 3rd party tool, want in pure bash

Tried emulating head with

head 5 15 15; shoul print only 5 line from output But for long number means long $2 $3 ($1 for fun); it halts. I wanted a non halting continuous output. Start looping and printf but stop at defined $max line.

Maybe using named pipe works
Can someone help me with this

Upvotes: 1

Views: 66

Answers (1)

Barmar
Barmar

Reputation: 781088

Pipe to a function that emulates head followed by one that emulates cat > /dev/null.

myhead() {
    for ((i = 0; i < $1; i++)); do
        read -r line
        printf "%s\n" "$line"
    done
}
catnull() {
    while read -r line; do :; done
}
fun 1 | { myhead 5; catnull; }

Upvotes: 2

Related Questions