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?
4 Answers
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!
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.
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.
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.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically