zsh strange piping behavior (compared to bash)

Viewed 64

Say I have a file test.sh that executes some command (ping in this case) in the background:

for i in $(seq 1 30); do
  # This `ping` will "sleep" for 10s
  ping 10.0.0.0 -w 10 >/dev/null &
  jobs -r | wc -l
done

If I run bash ./test.sh, I got the expected output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

However, if I run zsh ./test.sh, the output is unexpected:

0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0

What is "wrong" here? How can I get the same output in zsh as that of bash?

$ zsh --version
zsh 5.8 (x86_64-debian-linux-gnu)
$ bash --version
GNU bash, version 5.1.0(1)-rc3 (x86_64-pc-linux-gnu)
1 Answers

Replace

jobs -r | wc -l

with

[[ "$ZSH_NAME" == "zsh" ]] && setopt MONITOR
jobs -r | wc -l
[[ "$ZSH_NAME" == "zsh" ]] && setopt NO_MONITOR

to enable and disable job control only with zsh.

Related