You're hitting a common performance bottleneck in shell scripting: the overhead of establishing a new SSH connection for each iteration of a loop. Each connection involves authentication, key exchange, and session setup, which adds significant latency, especially when the remote commands are short.
Here are the most effective strategies to reduce the number of SSH connections, from simplest to most powerful:
This is often the easiest and most transparent solution. It reuses a single underlying TCP connection for multiple SSH sessions. While it still spawns a new sshprocess for each command, the expensive connection establishment phase happens only once.
How it works:
You configure SSH to create a "master" connection and subsequent SSH calls to the same host/user will piggyback on that existing connection.
Configuration (~/.ssh/config):
sshconfig
Host your_remote_host
User your_username
Hostname your_remote_host_ip_or_hostname
ControlMaster auto
ControlPath ~/.ssh/cm_sockets/%r@%h:%p
ControlPersist 60s # Keep the master connection open for 60 seconds after the last client disconnects
# (or 'yes' to keep it open indefinitely until explicitly killed)
Explanation:
ControlMaster auto: Automatically create a master connection if one doesn't exist, or join an existing one.
ControlPath: Specifies the path for the control socket. Make sure the directory ~/.ssh/cm_sockets/ exists (mkdir -p ~/.ssh/cm_sockets/).
ControlPersist 60s: The master connection will stay open for 60 seconds after the last client ssh process exits. This is ideal for loops, as subsequent ssh calls within that window won't re-authenticate. Use yes if you want it to stay open until you explicitly kill it (e.g., ssh -O exit your_remote_host).
Your Script (remains mostly the same):
bash
#!/bin/bash
for i in {1..100}; do
# Do something locally (e.g., prepare data, generate config)
LOCAL_DATA="local_value_$i"
# Run a command with ssh (this will now reuse the connection)
ssh your_username@your_remote_host "echo 'Remote command $i processed $LOCAL_DATA'"
# Potentially another SSH command
# ssh your_username@your_remote_host "another_remote_command $i"
done
Pros:
Minimal changes to your existing script.
Significantly reduces latency per ssh call.
Handles multiple ssh calls to the same host naturally.
Cons:
Still spawns multiple ssh processes.
Doesn't reduce the number of commands executed over SSH, just the connection overhead.
2. Combine Multiple Remote Commands into a Single SSH Call
This is often the most impactful solution if your local processing per loop iteration is minimal or can be passed as arguments, and your remote commands are simple.
How it works:
Instead of ssh "cmd1"; ssh "cmd2";, you do ssh "cmd1; cmd2;". For loop-based scenarios, this means building up a single, larger script to send over one SSH connection.
Method A: Semicolons or Logical Operators
Good for simple, sequential commands.
bash
#!/bin/bash
for i in {1..10}; do
LOCAL_DATA="local_value_$i"
LOCAL_FILE="file_$i.txt"
# Example: Create a local file and process it
echo "Content for $LOCAL_FILE" > "$LOCAL_FILE"
# Combine multiple remote commands with the local data
ssh your_username@your_remote_host "
echo 'Processing $LOCAL_DATA remotely';
REMOTE_VAR=$(cat /path/to/remote/file);
echo 'Remote var: '$REMOTE_VAR;
/path/to/remote/script.sh '$LOCAL_DATA'
"
rm "$LOCAL_FILE" # Clean up local file
done
Pros:
Very direct and easy to understand for a few commands.
Reduces ssh connections to one per loop iteration.
Cons:
Becomes unwieldy for complex logic or many commands.
Quoting and variable expansion ($LOCAL_DATA) can be tricky (the example shows proper quoting for a single variable).
Method B: Here-Document (<<EOF) - Sending a Multi-line Script
This is powerful for sending a complex, multi-line script to the remote host as a single SSH command.
bash
#!/bin/bash
for i in {1..10}; do
LOCAL_DATA="local_value_$i"
# Local operations...
# Send a multi-line script to the remote host using a here-document
ssh your_username@your_remote_host <<EOF
#!/bin/bash
# This entire block runs on the remote server
set -e # Exit immediately if a command exits with a non-zero status.
REMOTE_ARG_FROM_LOCAL="$LOCAL_DATA" # Local variable interpolated here!
echo "Remote processing for iteration $i"
echo "Received local data: \$REMOTE_ARG_FROM_LOCAL"
# More complex remote logic
if [ -d "/tmp/remote_dir" ]; then
echo "Directory exists."
ls -l /tmp/remote_dir
else
mkdir -p /tmp/remote_dir
echo "Directory created."
fi
# Run a remote script with the passed data
/path/to/remote/actual_script.sh "\$REMOTE_ARG_FROM_LOCAL"
echo "Remote processing finished for iteration $i."
EOF
done
Key Notes for Here-Documents:
Variable Expansion: Variables starting with $ inside the EOF block will be expanded by your local shell before being sent to the remote, unless you escape them (\$). This is crucial! In the example, "$LOCAL_DATA" is expanded locally, while \$REMOTE_ARG_FROM_LOCAL is passed literally and expanded by the remote shell.
set -e: Highly recommended inside the remote script part to ensure that if any command fails, the entire remote script (and thus the SSH command) exits immediately.
Indentation: You can use <<-EOF (with a hyphen) if you want to indent the here-document contents with tabs in your script without those tabs being sent to the remote.
Pros:
Maximum control over the remote execution logic.
Only one SSH connection per loop iteration.
Easily pass multiple local variables as arguments to the remote script.
Cons:
Requires careful handling of quoting and variable expansion (local vs. remote).
Output from the remote script can be harder to parse if you need specific values back.
Method C: Transferring a Script File and Executing It (for complex, reusable scripts)
If your remote logic is very complex, involves many lines, or needs to be reusable, it might be better to manage it as a separate script file.
bash
#!/bin/bash
REMOTE_SCRIPT_NAME="my_remote_script.sh"
REMOTE_SCRIPT_PATH="/tmp/$REMOTE_SCRIPT_NAME"
# Create the remote script content locally
cat > "$REMOTE_SCRIPT_NAME" <<'EOT'
#!/bin/bash
set -e
LOCAL_DATA_PASSED="$1" # This will be the argument from the SSH call
echo "Remote processing for iteration: $ITERATION_NUM" # Example of a variable from the main loop
echo "Received local data: $LOCAL_DATA_PASSED"
# ... more complex remote logic ...
/path/to/remote/complex_logic.py --data "$LOCAL_DATA_PASSED"
EOT
chmod +x "$REMOTE_SCRIPT_NAME" # Make it executable
for i in {1..10}; do
LOCAL_DATA="local_value_$i"
# 1. Transfer the script (only needs to be done once, or if it changes)
# (You might put this outside the loop if the script content doesn't change)
scp "$REMOTE_SCRIPT_NAME" your_username@your_remote_host:"$REMOTE_SCRIPT_PATH"
# 2. Execute the remote script, passing local data as arguments
ssh your_username@your_remote_host "$REMOTE_SCRIPT_PATH" "$LOCAL_DATA" "$i" # Pass $i as well if needed
done
rm "$REMOTE_SCRIPT_NAME" # Clean up local copy
Pros:
Clean separation of local and remote logic.
Remote script can be version-controlled independently.
Only one scp and one ssh connection per loop.
Cons:
Requires an extra scp step (though often you can scp the script before the loop starts if it doesn't change).
Variable passing is via command-line arguments, which is clean but might be limiting for many variables.
3. Offload the Loop Entirely to the Remote Server
If your "do something locally" part is minimal or can also be done on the remote server, or if the data can be prepared before the loop, you might move the entire loop to the remote server.
bash
#!/bin/bash
# Prepare ALL local data needed by the remote loop, potentially as a file
echo "value1" > local_data.txt
echo "value2" >> local_data.txt
# ... more values ...
# Or, if data can be generated on remote:
ssh your_username@your_remote_host <<'EOF'
#!/bin/bash
set -e
# Loop entirely on the remote server
for i in {1..100}; do
REMOTE_DATA="remote_value_$i" # Data generated on remote
echo "Remote loop iteration $i: Processing $REMOTE_DATA"
/path/to/remote/command_with_data.sh "$REMOTE_DATA"
done
# Or, if data was transferred:
# while IFS= read -r line; do
# echo "Processing data from file: $line"
# done < /path/to/remote/transferred_data.txt
echo "Remote loop finished."
EOF
rm local_data.txt # Clean up local file
Pros:
Only one SSH connection for the entire operation!
Minimizes network traffic once the connection is established.
Cons:
Requires that all necessary data and logic can be managed on the remote side.
Debugging can be harder as the entire loop runs remotely.
Getting results back to the local machine might require additional scp or redirecting output.
Which Method to Choose?
If your "local something" is truly independent and lightweight, and you have many distinct ssh calls in your loop, but each ssh call is very short (e.g., just ls, echo, touch):
Start with SSH Connection Sharing (ControlMaster). It's the least invasive.
If your "local something" prepares data that needs to be passed to the remote for a few related commands per loop iteration:
Combine Commands with a Here-Document (<<EOF). This is usually the best balance of flexibility and efficiency.
If your remote logic is a large, complex script that doesn't change often:
Transfer the script once (or conditionally) and then execute it in the loop.
If the entire operation, including the "local something" part, can be performed on the remote server (perhaps by transferring an input file once):
Offload the Loop Entirely to the Remote Server. This is the most efficient.
By carefully choosing one of these strategies, you can drastically reduce the overhead of SSH connections in your loop.