0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use SSH in Bash Script: Simple Guide with Examples

Use the ssh command inside a bash script to connect to a remote server and run commands. You write ssh user@host 'command' in the script to execute commands remotely over SSH.
📐

Syntax

The basic syntax to use SSH in a bash script is:

  • ssh user@hostname 'command': Connects to the remote host as user and runs the command.
  • user@hostname: The username and server address you want to connect to.
  • 'command': The command you want to run on the remote server, enclosed in quotes.
bash
ssh user@hostname 'command_to_run'
💻

Example

This example script connects to a remote server and lists files in the home directory.

bash
#!/bin/bash

# Connect to remote server and list files
ssh user@example.com 'ls -l ~/'
Output
total 8 -rw-r--r-- 1 user user 0 Jun 1 12:00 file1.txt -rw-r--r-- 1 user user 0 Jun 1 12:00 file2.txt
⚠️

Common Pitfalls

Common mistakes when using SSH in bash scripts include:

  • Not setting up SSH keys, causing password prompts that stop the script.
  • Forgetting to quote the remote command, which can cause syntax errors.
  • Not handling SSH connection errors, which can make scripts fail silently.

Always use SSH keys for passwordless login and quote commands properly.

bash
# Wrong way (no quotes, will cause error)
ssh user@example.com ls -l ~/

# Right way (quotes around command)
ssh user@example.com 'ls -l ~/'
📊

Quick Reference

CommandDescription
ssh user@host 'command'Run a command on remote host via SSH
ssh -i /path/to/key user@host 'command'Use specific SSH key for authentication
ssh -p 2222 user@host 'command'Connect to SSH on custom port 2222
ssh -o StrictHostKeyChecking=no user@host 'command'Skip host key checking (use with caution)

Key Takeaways

Use ssh user@host 'command' to run remote commands in bash scripts.
Set up SSH keys to avoid password prompts and enable automation.
Always quote the remote command to prevent syntax errors.
Handle SSH errors in scripts to avoid silent failures.
Use SSH options like -i for keys and -p for custom ports as needed.