Shell – How to pipe something to less over ssh

lessshellsshterminal

I am trying to configure a mutt binding to pipe an email into an ssh invocation to process the mail on a remote machine with a script that displays some output using less. However, this does not work, because less just gives me the entire output without paging.

Trying to narrow it down, what I am essentially trying to emulate is:

seq 1 100 | less

but with less running on the remote machine. (Because of my use case of calling the script in mutt, the seq 1 100 part (representing the email) cannot run on the remote machine, nor can the less part (representing the script with less) run on the local machine.)

If I do:

seq 1 100 | ssh -t REMOTE_MACHINE less

I get the warning "Pseudo-terminal will not be allocated because stdin is not a terminal." and less displays the output directly without doing any paging.

If I do:

seq 1 100 | ssh -t -t REMOTE_MACHINE less

less fails with "Missing filename ("less –help" for help)", so I guess its input is lost.

I also tried adding zsh -ic, with no effect. What is the right ssh invocation so that less on the remote host can read its standard input and do paging as usual?

Edit to try to answer Gilles' comment below: The problem also occurs if the less invocation in the examples above is replaced by an actual script. If I create an executable file script.sh containing:

#!/bin/bash

exec less

and I put this in my home in both the local and remote machine, then the following works:

seq 1 100 | ~/script.sh

but the following does not (with -t or -t -t or neither):

seq 1 100 | ssh REMOTE_MACHINE less

Best Answer

You can to pass the command as an argument and use -t to force pseudo terminal allocation.

For example if the seq command needs to run on the remote server:

ssh $REMOTE_HOST -t 'seq 1 100 | less'

If the seq command needs to run on the local machine, so you could use a similar command using inline string <<< (of course the quoting becomes a little difficult):

ssh $REMOTE_HOST -t "less <<< \"$(seq 1 100)\""
Related Question