bash - 手动 ping 已关闭,但显示了 shell 脚本
问题描述
- 手动 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>
- 我希望得到以下输出。
期望的输出
user@CiscoAPIC> ./script3.sh
Nexus01 - 10.1.1.1 is down
Nexus02 - 10.1.1.2 is up
user@CiscoAPIC>
解决方案
问题
管道的退出代码是管道中最后一个命令的退出代码。
考虑:
ping -c 1 "$h" | head -1 | cut -d ' ' -f3 | tr -d '()'
if [ $? -eq 0 ]; then
语句看到的退出代码 是 的退出$?
代码。您想要.if
tr -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")
这表明false
exited with code 1
。因此,在您的代码中,替换:
if [ $? -eq 0 ]; then
和:
if [ "${PIPESTATUS[0]}" -eq 0 ]; then # Bash only
推荐阅读
- javascript - Firebase 错误:运行 Jest 测试时浏览器不受支持
- php - Kubernetes 命名空间环境标头
- css - 更改 FontAwesome 跨度图标的悬停颜色
- reactjs - Intellij 发现路径不适用于反应项目中的公共/脚本
- python - 使用 matplotlib 和 pandas 用虚线创建事件的时间图
- android - 在 rxjava2 中的异步请求完成之前调用订阅者 onNext
- php - 检查 PHP 中的路径遍历并允许使用未损坏的非现有路径
- java - 无法将 TextView 转换为 java.io.Serializable
- asp.net - Visual Studio 2017 Angular 6 显示“无法获取 /”,仅限首次尝试
- loops - 使用 Jinja2 模板循环访问主机