Sometimes you want your cron job to run only if a specific TCP service is available — for example, a database, API endpoint, or SSH service.

In this article, you'll learn how to run a cron job only when a TCP port is open, using just built-in tools like timeout, bash, and echo.

🛠️ Why Not Just Use ping?

ping checks if a host is reachable via ICMP — but:

  • Many servers block ICMP
  • Ping doesn't verify a specific port (e.g., 22 for SSH, 5432 for Postgres)

So instead, we can use TCP probing.

✅ Quick One-Liner to Check a TCP Port

Here's the syntax:

timeout 1 bash -c 'echo > /dev/tcp/192.168.1.100/22' && echo "Port open" || echo "Port closed"

Explanation:

  • timeout 1: Waits max 1 second.
  • bash -c 'echo > /dev/tcp/HOST/PORT': Tries to open a TCP connection.
  • &&: Only run next command if the port is open.
  • ||: Fallback if it's closed or unreachable.

🕒 Crontab Example: Run Only If TCP Port Is Open

Let's say you want to run a script only if your internal database is reachable on port 5432:

* * * * * timeout 1 bash -c 'echo > /dev/tcp/192.168.1.100/5432' && /home/user/sync-db.sh

This checks connectivity to 192.168.1.100:5432 and only runs /home/user/sync-db.sh if the port is open.

📁 Example 2: Using with a Private IP

*/5 * * * * timeout 1 bash -c 'echo > /dev/tcp/10.0.0.5/22' && /home/user/ssh-backup.sh

✅ Works with:

  • Public servers (e.g., example.com on port 443)
  • Private hosts (like your router or internal server)

🧪 Example 3: Log Result to File

* * * * * timeout 1 bash -c 'echo > /dev/tcp/192.168.1.100/80' && echo "$(date) - Web Server Online" >> /tmp/port-check.log || echo "$(date) - Web Server Offline" >> /tmp/port-check.log

📦 Pro Tip: Wrap in a Script

Create a reusable script like this:

#!/bin/bash

HOST="192.168.1.100"
PORT="3306"
CMD="/home/user/backup-mysql.sh"

if timeout 1 bash -c "echo > /dev/tcp/$HOST/$PORT" 2>/dev/null; then
    $CMD
else
    echo "$(date) - $HOST:$PORT not reachable" >> /var/log/port-check.log
fi

Call it from cron:

*/10 * * * * /home/user/check-port-and-run.sh

✅ When Is This Useful?

  • Check if a PostgreSQL or MySQL DB is ready before running backups
  • Confirm a web service is running before deploying
  • Ensure SSH is open before pushing configs

🔐 Final Thoughts

Checking a TCP port is often more reliable than ping, especially in firewalled environments. Using timeout, bash, and redirection to /dev/tcp, you can build lightweight and effective network-aware cron jobs — no external tools needed!