Bilal Akil
Bilal Akil

Reputation: 4755

Strange behaviour when copy/pasting bash commands with heredocs into terminal

To simplify some processes I document a large series of terminal commands so I can copy and paste them when needed.

I'm encountering some strange behaviour however, as demonstrated here:

ssh $USER@$SERVER 'rm ~/backup.tar'

tar -xvzf backup.tar
cd backup

When I copy all of that and paste it into a terminal, the SSH command is executed, resulting in a pause as it runs. Once it finishes, the tar and cd commands are not executed - as if they were never copied.

I surmise this is because they're somehow being "typed" (I know that's not the right word) while the SSH command is still executing, and are hence consumed by that command - doing nothing there.

Sure, that makes sense, but it gets weird here:

ssh $USER@$SERVER 'rm ~/backup.tar' <<EOF
EOF

tar -xvzf backup.tar
cd backup

This seems like the same thing but with some random, purposeless heredoc. However when I've got it there, the tar and cd commands are successfully pasted and executed after the SSH command completes.

And so my question:

What difference did the heredoc make that caused tar and cd to be pasted as I would've originally expected?

Is there a better way than randomly slugging on a heredoc to achieve the same result?

Upvotes: 2

Views: 439

Answers (3)

David Z
David Z

Reputation: 131740

When you run a command normally, the standard input of the process is connected to the terminal. Any characters that the terminal program receives are passed on to the process. But when you run a command with a redirection, like the heredoc you used, the standard input of the process is connected to a memory buffer containing the contents of the heredoc. In this case, characters the terminal program receives don't get passed on to the process; instead, they get saved, and after the process finishes, then the terminal program figures out what to do with them.

As far as how to fix it: the best way is probably to use a shell script, instead of copying and pasting. But if you can't do that for some reason, the redirection seems like a reasonable solution. Instead of providing a heredoc you could just run

ssh $USER@$SERVER 'rm ~/backup.tar' </dev/null

Upvotes: 2

Anton Krosnev
Anton Krosnev

Reputation: 4132

In first example tar and cd command went to stdin of ssh. In the second the stdin of ssh was terminated and therefore bash executed tar and cd

Upvotes: 0

choroba
choroba

Reputation: 242333

ssh reads standard input. If you supply a HERE doc, it takes its input from it, so doesn't read the real stdin with the commands.

Upvotes: 0

Related Questions