On Debian, how to run a given command COMMAND when another (like `sleep 5`) starts?
Yesterday 3:52pm

To run a command (COMMAND) when another command (like sleep 5) starts on Debian (or any Linux system), you can use a combination of shell features. Here are two approaches:


1. Using & and wait in a Shell Script

If you want COMMAND to run immediately when sleep 5 starts, you can use backgrounding (&) and a subshell:

bash
(sleep 5 & COMMAND)
  • sleep 5 & runs sleep 5 in the background.
  • COMMAND runs immediately after sleep 5 starts.

Example:

bash
(sleep 5 & echo "Sleep started, running COMMAND now")

This will print "Sleep started, running COMMAND now" as soon as sleep 5 begins.


2. Using pidof or pgrep to Detect Process Start

If you want COMMAND to run only after confirming sleep 5 has started, you can use a loop to check for the process:

bash
sleep 5 &
while ! pidof sleep > /dev/null; do
    sleep 0.1
done
COMMAND
  • sleep 5 & starts sleep 5 in the background.
  • The while loop checks if sleep is running using pidof.
  • Once sleep is detected, COMMAND runs.

Example:

bash
sleep 5 &
while ! pidof sleep > /dev/null; do
    sleep 0.1
done
echo "Sleep started, running COMMAND now"

3. Using inotifywait (Advanced)

If you want to trigger COMMAND when a specific process file (e.g., /proc/PID) appears, you can use inotifywait (from the inotify-tools package):

bash
sudo apt install inotify-tools
sleep 5 &
inotifywait -e create /proc/$(pgrep -f "sleep 5") && COMMAND
  • This waits for the /proc/PID directory to be created for the sleep 5 process.
  • Once detected, COMMAND runs.

Which One to Use?

  • For immediate execution, use Approach 1 ((sleep 5 & COMMAND)).
  • For process confirmation, use Approach 2 (pidof loop).
  • For file-based triggers, use Approach 3 (inotifywait).
Yesterday 3:52pm

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

Vibe can make mistakes. Check answers. Learn more