• InfraCoffee
  • Posts
  • Waiting for a Process to Finish? Ditch sleep—Do This Instead!

Waiting for a Process to Finish? Ditch sleep—Do This Instead!

Because staring at the terminal won’t make it go faster

Ever needed your Bash script to wait for a command to complete but didn’t know how long it would take?

❌ Bad: Using a fixed sleep 10 wastes time (what if it finishes in 2 seconds?).

✅ Better: Use wait (for child processes) or tail --pid= (for any PID)!

1. For Background Processes (Child of Shell)

your_command & # Launch in background

pid=$! # Capture PID

wait "$pid" # Synchronous wait

echo "Done!"

2. For Any External Process (Even Outside Shell)

tail --pid=12345 -f /dev/null # Blocks until PID 12345 exits

echo "Process finished!"

🔥 Why?

✔ No guessing (unlike sleep).

✔ Efficient (no CPU waste like while kill -0 loops).

✔ Works for any PID (not just child processes).

📌 Use Case:

Waiting for a long-running script before the next step.

Ensuring a server/container finishes before cleanup.

💡 Pro Tip: Combine with timeout to avoid infinite waits!

Have you used a smarter alternative? Share in the comments! 👇