5

It appears that in this question, the answer was to separate statements with semicolons. However that could become cumbersome if we get into complex scripting with multiple if statements and complex quoted strings. I would think.

I imagine another alternative would be to simply issue multiple SSH commands one after the other, but again that would be cumbersome, plus I'm not set up for public/private key authentication so this would be asking for passwords a bunch of times.

What I'd ideally like is much similar to the interactive shell experience: at one point in the script you ssh into@the_remote_server and it prompts for the password, which you type in (interactively) and then from that point on until your script issues the "exit" command, all commands in the script are interpreted on the remote machine.

Of course this doesn't work:

ssh user@host.com
  cd some/dir/on/remote/machine
  tar -xzf my_tarball.tgz
  cd some/other/dir/on/remote
  cp -R some_directory somewhere_else
exit

Is there another alternative? I suppose I could take that part right out of my script and stick it into a script on the remote host. Meh. Now I'm maintaining two scripts. Plus I want a little configuration file to hold defaults and other stuff and I don't want to be maintaining that in two places either.

Is there another solution?

Community
  • 1
  • 1
Tom Auger
  • 18,326
  • 22
  • 73
  • 100

2 Answers2

9

Use a heredoc.

ssh user@host.com << EOF
cd some/dir/on/remote/machine
tar -xzf my_tarball.tgz
cd some/other/dir/on/remote
cp -R some_directory somewhere_else
EOF
Ignacio Vazquez-Abrams
  • 699,552
  • 132
  • 1,235
  • 1,283
  • as your heredoc script gets more complicated (with variables particularly), you'll want to quote the heredoc delimter: `<< 'EOF'`. Then, the heredoc will be sent literally to the remote machine and your local shell won't try to interpret it. – glenn jackman Jul 15 '11 at 13:57
3

Use heredoc syntax, like

ssh user@host.com <<EOD
 cd some/dir/on/remote/machine
 ...
EOD

or pipe, like

echo "ls -al" | ssh user@host.com
wonk0
  • 12,163
  • 1
  • 18
  • 13