I'm looking for help with a script that takes a set of commands as an argument to execute after a certain process ends. I often back up to different external HDDs, and each model has its own spin-down time. Once a backup is done, I want to perform various actions afterward, such as shutting down the disk, taking a snapshot, or moving files. For example, I'd like to run a command like `./script 3872 "sudo defragment /media/hdd; sudo shutdown hdd"`, where 3872 is the PID of the rsync command. I could chain the commands together, but passing the PID instead allows for more flexibility without needing to restart the process. I was thinking of using a while loop to check for `pidof 3872` but am unsure how to best pass an arbitrary set of commands to the script. Any thoughts or better approaches for handling queued commands for different processes?
2 Answers
To handle your situation effectively, you want to keep your backup process separate from the post-backup tasks. An approach could look like this:
```bash
backup &
backup_pid=$!
while pid_still_going $backup_pid; do
sleep 1
done
post_backup_cmd1
post_backup_cmd2
post_backup_cmd3
```
This way, you run the backup in the background, then poll for its completion before starting your next commands. This keeps everything organized and also allows you to adjust your post-backup commands without redoing the backup.
If you're using Linux, you can utilize the GNU `tail` command with the `--pid` flag to run commands after your process exits:
```bash
tail --pid="$pid" -f /dev/null && sh -c "$*"
```
This setup will ensure that the tail command keeps checking until your specified process dies, at which point it will execute your command. If your process is a child process, just using `wait $pid` might also suffice!

Great tip! I was considering how to set up a trap to manage the exit codes, but this seems simpler and more effective.