Instead of counting number of scrolled lines ... could counting the number of lines of output from the command may be of benefit?
For example, if the terminal has 20 lines (tput lines
) and the command output 40 lines then you know the 'scroll' was 20 lines (+/- depending on how you count the follow-on console/command prompt).
NOTE: at the moment I'm drawing a blank on (if?) how to determine the current line in the window (eg, 10 lines of output start at line 18 in a 20-line window, so scroll would be 8); could you force a clear
to insure output always starts on line 1 ('at the top')?
Per this Q&A: Count number of lines of output, one idea:
outcnt=$(command 2>&1 | tee /dev/stderr | wc -l)
Taking for a test drive:
$ outcnt=$(printf "%s %s\n" {1..10} 2>&1 | tee /dev/stderr | wc -l)
1 2
3 4
5 6
7 8
9 10
$ typeset -p outcnt
declare -- outcnt="5"
This particular example will also count stderr in the count:
$ outcnt=$(non-existent command 2>&1 | tee /dev/stderr | wc -l)
-bash: non-existent: command not found
$ typeset -p outcnt
declare -- outcnt="1"
If you don't want to count stderr lines then remove the 2>&1
:
$ outcnt=$(non-existent command | tee /dev/stderr | wc -l)
-bash: non-existent: command not found
$ typeset -p outcnt
declare -- outcnt="0"
Example of counting stdout but not stderr:
$ outcnt=$( { echo "hello"; non-existent command; } | tee /dev/stderr | wc -l)
-bash: non-existent: command not found
hello
$ typeset -p outcnt
declare -- outcnt="1"
A variation on this approach, especially if you can't/don't want to use outcnt=$(...)
, would be to have tee
redirect a copy of the output to a file and then wc -l
the file.