Linux/Unix Shell Scripting Examples: SSH

Last updated:
Table of Contents

WIP Alert This is a work in progress. Current information is correct but more content may be added in the future.

Unless otherwise defined, examples are written in the bash dialect

SSH using a private key

TODO. also post a link on how to create a key pair, permissions, etc

SSH command options

TODO -i, -q, -t (explain how it fixes the warning message)

SSH to another machine and run arbitrary commands

The "ENDSSH"...ENDSSH block is a HEREDOC multi-line string.

The quotes around the first ENDSSH marker tell bash you don't want it to perform variable expansion within the block.

#!/usr/bin/env bash

# you can add other options to the ssh command too
ssh myusername@remotehost << "ENDSSH"
cd /home/myusername
ls -lha
ENDSSH

If you also want to retrieve the output and store it in a variable, do this:

#!/usr/bin/env bash

output=$(ssh myusername@remotehost << "ENDSSH"
cd /home/myusername
ls -lha
ENDSSH)

# do something with the results
echo "$output"

Dialogue & Discussion