Rhyknowscerious Rhyknowscerious - 14 days ago 10
Bash Question

Scroll linux shell script output without piping

I have a linux bash script.sh. I can easily scroll the output like this:

$ ./script.sh | less


But how do I make the output display scrollable automatically, without having to pipe it through "less"? In other words, how do I put that functionality right into the script itself? I just want to execute the script like this:

$ ./script.sh


I know I might be able to write a different script to execute the first one and pipe the output automatically but I don't want to have to write another script just to get the first one to do what I want it to do. Know what I mean?

Answer

You can write your script like this:

#!/bin/bash
(

    Your script here

) | less
exit $PIPESTATUS 

This will pipe the script output through less if output is a terminal (so you can ./script.sh > file without paging), and it preserves the script's exit code.