#!/bin/bash set -e kill_foreground() { echo "Background script has finished. Killing foreground script." ps -C "test3.sh" -o "%p"| grep -v PID | xargs kill; } kill_background() { echo "Foreground script finished. Killing background script." kill 0; } trap "exit" INT TERM trap "kill_background" EXIT ./test2.sh & export PID1=$! ( tail -f --pid=$PID1 /dev/null; echo "kill test3.sh "; kill_foreground ) & ./test3.sh