首页 > 解决方案 > 手动 ping 已关闭,但显示了 shell 脚本

问题描述

  1. 手动 ping 已关闭,但显示了 shell 脚本

脚本3.sh

#!/bin/bash
cat host.txt |  while read h
do
    ping -c 1 "$h" | head -1 | cut -d ' ' -f3 | tr -d '()'
    if [ $? -eq 0 ]; then
                echo "$h is up"
    else
                echo "$h is down"
    fi
done

输出

user@APIC> ./script3.sh
10.1.1.1
Nexus01 is up
10.1.1.2
Nexus02 is up
user@APIC>

手动 ping 显示 Nexus01 (10.1.1.1) 当前已关闭

user@APIC> ping Nexus01 -c 1
PING Nexus01 (10.1.1.1) 56(84) bytes of data.

--- Nexus01 ping statistics ---
1 packets transmitted, 0 received, 100% packet loss, time 0ms

user@APIC>

user@APIC> ping Nexus02 -c 1
PING Nexus02 (10.1.1.2) 56(84) bytes of data.
64 bytes from Nexus02 (10.1.1.2): icmp_seq=1 ttl=64 time=0.171 ms

--- Nexus02 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.171/0.171/0.171/0.000 ms
user@APIC>
  1. 我希望得到以下输出。

期望的输出

user@CiscoAPIC> ./script3.sh
Nexus01 - 10.1.1.1 is down
Nexus02 - 10.1.1.2 is up
user@CiscoAPIC>

标签: bash

解决方案


问题

管道的退出代码是管道中最后一个命令的退出代码。

考虑:

ping -c 1 "$h" | head -1 | cut -d ' ' -f3 | tr -d '()'
if [ $? -eq 0 ]; then

语句看到的退出代码 是 的退出$?代码。您想要.iftr -d '()'ping

我们可以用一个更简单的管道来证明这一点:

$ false | tr -d '()'; echo $?
0
$ true | tr -d '()'; echo $?
0

在这两种情况下,上面的退出代码都是成功 ( 0)。即使false返回退出代码也是如此1

解决方案

如果您正在运行 bash (不是sh),那么您寻找的退出代码在 shell 数组中可用PIPESTATUS。例如:

$ false | tr -d '()'; declare -p PIPESTATUS
declare -a PIPESTATUS=([0]="1" [1]="0")

这表明falseexited with code 1。因此,在您的代码中,替换:

if [ $? -eq 0 ]; then

和:

if [ "${PIPESTATUS[0]}" -eq 0 ]; then   # Bash only

推荐阅读