white_gecko white_gecko - 1 month ago 10
Bash Question

Refere to jobs in sh

In bash I can refer to the last job with

%+
or
%%
but I can't do that in
/bin/sh
.

Considering the following script:

#!/bin/[ba]sh

some_job() {
sleep 1
sleep 1
sleep 1
sleep 1
sleep 1
sleep 1
}

some_other_job() {
sleep 1
}

echo "some_job"
some_job &

echo "some_other_job"
some_other_job &

echo "sleep"
sleep 2

kill %1

jobs -l


running it with
bash
is fine, but executing it with
sh
gives me an error.

$ ./mwe.sh
some_job
some_other_job
sleep
./mwe.sh: 25: kill: No such process

[2] + 2446 Done
[1] + 2445 Running
$ ps
PID TTY TIME CMD
2445 pts/0 00:00:00 mwe.sh
2453 pts/0 00:00:00 sleep
2494 pts/0 00:00:00 ps
3587 pts/0 00:00:01 zsh


How can I refer to jobs in
/bin/sh
?

Answer

POSIX kill only works with process ids, not jobspecs. You'll have to explicitly record the process ID of the job you want to kill.

# [ function definitions deleted.]

echo "some_job"
some_job & to_kill=$!

echo "some_other_job"
some_other_job &

echo "sleep"
sleep 2

kill "$to_kill"

jobs -l