I think the only way to do it would be to use separate commands depending on what you're passing it.
First of all, for easy demonstration, I'll create two variables, one containing 4 lines of text, the other containing 20 lines of text.
SmallVar=$(cat <<EOF
01 SmallVar
02 A
03 B
04 C
EOF
)
LargeVar=$(cat <<EOF
01 LargeVar
02 A
03 B
04 C
05 D
06 E
07 F
08 G
09 H
10 I
11 J
12 K
13 L
14 M
15 N
16 O
17 P
18 Q
19 R
20 S
EOF
)
echo
echo "Lines in SmallVar: $(echo "${SmallVar}" | wc -l)"
echo "Lines in LargeVar: $(echo "${LargeVar}" | wc -l)"
echo "Lines available in terminal: $(tput lines)"
echo
The output of the above is:
Lines in SmallVar: 4
Lines in LargeVar: 20
Lines available in terminal: 15
These are all on one line, but could be split to multiple for easy reading. tmpVar
is the variable or file content you're passing.
(if you're passing a file content, you can use tmpVar="$(cat filename.txt"
)
Short List
tmpVar="${SmallVar}"; if [ $(echo "${tmpVar}" | wc -l) -le $(tput lines) ]; then echo "${tmpVar}" | less -FX; else echo "${tmpVar}" | less +G -FX; fi;
Long list
tmpVar="${LargeVar}"; if [ $(echo "${tmpVar}" | wc -l) -le $(tput lines) ]; then echo "${tmpVar}" | less -FX; else echo "${tmpVar}" | less +G -FX; fi;
It is probably easier to read it split into separate lines:
tmpVar="${SmallVar}";
#tmpVar="${LargeVar}";
if [ $(echo "${tmpVar}" | wc -l) -le $(tput lines) ];
then
echo "${tmpVar}" | less -FX;
else
echo "${tmpVar}" | less +G -FX;
fi;
First it does an if
to compare the number of lines in the variable against the number of lines in the terminal (run tput lines
on its own, resize the window and run again). If it's equal-to or less than, it ignores the +G
. Otherwise, it'll use the +G
. The -X
is used to leave the values on screen after it exits. When you press q to quit, it keeps the last few lines on screen without clearing them.
Compare
$ tmpVar="${SmallVar}"; if [ $(echo "${tmpVar}" | wc -l) -le $(tput lines) ]; then echo "${tmpVar}" | less -FX; else echo "${tmpVar}" | less +G -FX; fi;
01 SmallVar
02 A
03 B
04 C
$
with
$ tmpVar="${LargeVar}"; if [ $(echo "${tmpVar}" | wc -l) -le $(tput lines) ]; then echo "${tmpVar}" | less -FX; else echo "${tmpVar}" | less +G -FX; fi;
...........[scroll]...........
07 F
08 G
09 H
10 I
11 J
12 K
13 L
14 M
15 N
16 O
17 P
18 Q
19 R
20 S
(END)