How to Keep an SSH Connection Alive Without Changing Config Files?

February 1, 2026 4 answers
Asked by CuriousCoder99
I'm running a Bash script that needs to wait for a user to finish a task in the GUI before proceeding. However, sometimes the user takes too long, and the SSH connection drops. I'm looking for a way to modify the script so that it pings the server or sends a command like "cat file" every 20 seconds to keep the connection active while waiting for user input with "read -r answer". Any suggestions on how to implement this?

Answers

HelpfulTechie22
You can use the SSH command with options to keep your connection alive without modifying any configuration files. Try this command: ``` ssh -o ServerAliveInterval=60 -o ServerAliveCountMax=60 user@hostname ``` This sends an empty packet to the server every 60 seconds, which effectively keeps your connection alive for up to an hour. Adjust the timing as needed based on your server's specific requirements.
Reply to this answer
CodeWhisperer77
A neat trick is to start a background loop that sends a non-printing character every 20 seconds to keep the connection open. You can implement it like this: ``` while true; do sleep 20; echo -ne ""; done & HEARTBEAT_PID=$! read -r answer kill $HEARTBEAT_PID ``` This way, the connection should stay alive while waiting for the user's input.
Reply to this answer
RemoteExpert34
Have you checked out mosh? It's designed for mobile SSH connections and can handle intermittent network connections better than standard SSH, which could be really useful in your case.
Reply to this answer
TmuxEnthusiast
If you often run into this issue, I highly recommend using tmux. It's like having another layer of bash. Start a tmux session with: ``` tmux new -t sessionname ``` If you get disconnected, you can reconnect to the server and reattach the tmux session with: ``` tmux attach -t sessionname ``` It's really stable and offers a lot of other features!
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions