At one point, you were close to what you seem to want.
echo "a.sh running"
(sleep 10s; pkill -f b.sh) &
pkill -f b.sh
echo "a.sh still running"
b.sh (same as your version)
echo "b is now running"
(sleep 10s; pkill -f b.sh) & line in
creates a subshell that sleeps for ten seconds and then kills
It then puts that subshell into the background,
a.sh can keep running.
a.sh then runs
b.sh, which runs
Ten seconds later, the
sleep 10s in the subshell finishes,
and it (the subshell) runs
pkill -f b.sh, killing the
a.sh then resumes running.
pkill -f b.sh does nothing,
b.sh process is already terminated.
This is what happens when it runs:
a.sh running # immediately
b is now running # about 10 seconds after the above
./a.sh: line 6: 13684 Terminated bash b.sh # about 10 seconds after the above
a.sh still running # about 10 seconds after the above
$ # immediately after the above
This has the advantage that
a.sh can resume running immediately
b.sh finishes quickly.
b.sh runs for more than 10 seconds does the
pkill kick in.
In the other answer,
a.sh has to sit idle
sleep before the
pkill takes up time,
b.sh has already wrapped up.
Another user posted a comment (now deleted) saying
b is now running
not what you report. Any idea?
It was a dark and stormy night. Suddenly, a shot rang out!
—It Was a Dark and Stormy Night, Snoopy
by Charles M. Schulz
The argument to
pkill is a regular expression;
specifically, an Extended Regular Expression1.
pgrep c.t — it will list two PIDs,
and you can confirm with
ps that they are
If you had done exactly what I said,
you really should have gotten the same results I did.
But I’m willing to wager 42 Zorkmids that you did something different.
#!/bin/bash as a she-bang (first line)
bash a.sh instead of
Suddenly, a shot rang out!
b.sh is a regular expression that matches
followed by any character followed by
It matches itself (
and also things like
And … … (wait for it) … … it also matches
pkill -f b.sh kills all bash processes,
and also any others that have
b.sh in their names.
When I ran what I ran, my login shell
(which is at least partially immune to
pkill) was bash,
a.sh was running under
b.sh was running under
pkill -f b.sh command killed the
bash b.sh process
because it contained both
/bin/sh that was running
a.sh was unaffected.
Assuming you ran it the way I believe you ran it
(either of the two alternatives),
all the script processes were running
And so the
pkill -f b.sh command killed all the script processes.
pkill -f b.sh to
pkill -f 'b\.sh'
(escaping the dot so it matches only a dot, and not any character),
and you should get the right results.
2 If you have two terminals (shell windows),
cat | cut -f1 (with input from the terminal) in one of them,
p-commands in the other.
If you have only one terminal,
sleep 42 | cat | cut -f1 &
sleep, the pipeline would collapse immediately),
and then run
p-commands in the same window.