Bash – Use `cat` or `less` Depending on Line Count

catless

When looking at the content of files, I'd like to automatically cat short files but less those that exceed the screen size. I could use something with wc -l, but is there a better way that maybe also considers the window size / current amount of lines available?

Best Answer

To give you the formula which involves the wc-based check:

(($(wc -l<input_file)<=$(tput lines))) && echo 'will fit' || echo 'not enough'

There is a $LINES shell variable which can also be used:

(($(wc -l<input_file)<=LINES)) && echo 'will fit' || echo 'not enough'

But $LINES is updated only when at the command prompt. To understand what I mean, run this and resize the terminal window during the sleep:

( sleep 3; echo $LINES; tput lines )
Related Question