linux命令执行情况返回值

linux 执行ping命令使用 $? 查看命令执行情况:


mark@localhost:~/Documents/linux> ping 192.168.241.21 -c 1
PING 192.168.241.21 (192.168.241.21) 56(84) bytes of data.
64 bytes from 192.168.241.21: icmp_seq=1 ttl=64 time=0.035 ms
--- 192.168.241.21 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.035/0.035/0.035/0.000 ms
mark@localhost:~/Documents/linux> echo $?
0
mark@localhost:~/Documents/linux> ping 192.168.241.22 -c 1
PING 192.168.241.22 (192.168.241.22) 56(84) bytes of data.
From 192.168.241.21 icmp_seq=1 Destination Host Unreachable
--- 192.168.241.22 ping statistics ---
1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 0ms
mark@localhost:~/Documents/linux> echo $?
1
mark@localhost:~/Documents/linux> 

但是使用脚本时出现异常:

#!/bin/bash
for a in $(seq 21 1 22)
do
        echo "$a"
        ping 192.168.241.$a -c 3 > out
        cat out
        echo $?
        if [ $? == 1 ]; then
                cat out >> std
        else
                cat out >> err
        fi
done
~      

结果如下:

sh a.sh 
21
PING 192.168.241.21 (192.168.241.21) 56(84) bytes of data.
64 bytes from 192.168.241.21: icmp_seq=1 ttl=64 time=0.018 ms
64 bytes from 192.168.241.21: icmp_seq=2 ttl=64 time=0.027 ms
64 bytes from 192.168.241.21: icmp_seq=3 ttl=64 time=0.046 ms
--- 192.168.241.21 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2048ms
rtt min/avg/max/mdev = 0.018/0.030/0.046/0.012 ms
0
22
PING 192.168.241.22 (192.168.241.22) 56(84) bytes of data.
From 192.168.241.21 icmp_seq=1 Destination Host Unreachable
From 192.168.241.21 icmp_seq=2 Destination Host Unreachable
From 192.168.241.21 icmp_seq=3 Destination Host Unreachable
--- 192.168.241.22 ping statistics ---
3 packets transmitted, 0 received, +3 errors, 100% packet loss, time 2040ms
pipe 3
0

请问哪个大是可以帮忙解决一下

输出结果位置不正确,输出位置应该放在ping命令之后,cat out应该放在fi之done之前