I have a command (a compiler) that can output lots to the terminal when there's a compilation problem. Some of the lines are longer than my terminal is wide, and it also uses terminal colours (red text for errors etc). I want to run that command, and only show the first screen/page of output, but taking account of line wraps & colours.

Update I am using cargo, the Rust compiler, and if there's a syntax error, it will produce lots of output, including colours. with --colors=always, and |& I can show both. e.g. cargo build --colors=always |& head -n 20 shows the first 20 lines. I want to show the first page only, so that I can

I use entr to auto run find ./src/ -type f -name '*.rs' | entr -r bash -c 'cargo build -- color=always |& less -R will not work, because the less command gobbles everything and I can't stop it. In fact that hides all output.

  • 1
    Have you tried piping your output to less with -RS and scrolling horizontally with your arrow keys? yourcommand | less -RS. – Kahn Jun 23 '20 at 13:32
  • @Kahn I think less -R is the way to go, because OP wants to keep wraps, not remove them. – Quasímodo Jun 23 '20 at 13:34
  • @Quasímodo yep - I wasn't really understanding that part. Thanks for the clarity. – Kahn Jun 23 '20 at 13:38

Sounds like you're just looking for less -R:

          Like  -r,  but  only ANSI "color" escape sequences are output in
          "raw" form.  Unlike -r, the screen appearance is maintained cor‐
          rectly  in  most  cases. 

That flag tells less to interpret ANSI color sequences, so the output should be just the same as on your terminal.

If all you want is to get the first N lines where N is the current size of your terminal window, use $LINES:

find ./src/ -type f -name '*.rs' | 
    entr -r bash -c 'cargo build -- color=always |& head -n $LINES

Or, since the prompt when you launch the command and the one printed after it finishes both take up one line:

find ./src/ -type f -name '*.rs' | 
    entr -r bash -c 'cargo build -- color=always |& head -n $((LINES-2))
  • That's part of the way there, but it lauches an interactive terminal programme, rather than stopping at the first page. I just want the output to be the first page. – Rory Jun 23 '20 at 15:07
  • @Rory OK, could you edit your question then and tell us what compiler you are using? Are the ANSI sequences kept if you redirect/pipe the output (many tools detect when they are being piped or redirected and remove the colors)? If they are kept, it's very easy, but if not it can get more complicated. – terdon Jun 23 '20 at 15:18
  • I'm using cargo, Rust's compiler. It has a --color=always flag, so I can ensure the colours are there – Rory Jun 24 '20 at 10:12
  • @Rory ah, good. So how do you define a page? How may lines? – terdon Jun 24 '20 at 10:12
  • “page” = “one screenful of my current terminal” – Rory Jun 25 '20 at 13:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.