Stop writing infinite loops to test your service health

Shell Scripting / Bash Tricks

Stop writing infinite loops to test your service health

🧩 The Challenge

Dealing with a service that takes forever to bind to a port during a reboot or deployment is a headache. You’ve probably written those ugly while-true loops with sleep commands that just clutter up your init scripts.

💡 The Fix

Bash has a built-in feature for network connections that makes polling a remote port native and incredibly clean. It saves you from installing netcat or extra dependencies just to wait for a socket to open.

until 2>/dev/null >/dev/tcp/127.0.0.1/8080; do
echo "Waiting for service..."
sleep 2
done
echo "Service is up!"

⚙️ Why It Works

Bash opens a special file descriptor pointing to that TCP address when you use the /dev/tcp syntax, and it returns a non-zero exit status if the connection fails. Checking that status in an until loop is way faster than spawning a subprocess for every single check.

🚀 Pro-Tip: Use this inside your Docker entrypoint scripts to keep containers from starting until the database is actually ready.

Linux Tips & Tricks | © ngelinux.com | 11/25/2026

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted