【问题标题】:Waiting for network link to be up before continuing in bash [duplicate]等待网络链接启动,然后继续 bash [重复]
【发布时间】:2026-02-22 13:10:01
【问题描述】:

在继续之前,有没有办法在 bash 脚本中检查多个接口的网络接口链接是否成功?

类似:

eth0 eth1 eth2 eth3 network interfaces are brought up
Wait for link detection on all 4 interfaces
Proceed

【问题讨论】:

  • 在一个循环中尝试每秒 1 次 ping 到某个已知主机的每个网络中的内容,或者检查 ifconfig 输出...
  • 如果它们是 up 的,并不一定意味着其他主机响应 ping。

标签: bash networking ping ifconfig


【解决方案1】:

您可以在运行ifconfig -s 后检查网络接口的名称是否出现。

类似:

if [ $( ifconfig -s | grep eth0 ) ]; then echo "eth0 is up!"

查看this link 了解更多详情。


要进行此测试,您可以执行@jm666 所说的类似操作:

while ! ping -c 1 -W 1 1.2.3.4; do
    echo "Waiting for 1.2.3.4 - network interface might be down..."
    sleep 1
done

【讨论】:

  • 如果我只想测试一次这很好,但如果我需要积极等待它上线然后继续呢?
  • 为什么你有一个-W 标志在那里?您没有为单个 ping 指定超时......
  • -c 1 -W 1 表示“尝试 1 个回显,最多等待 1 秒”。如果它没有收到回显,则进入 if 块,显示消息,并等待一秒钟,然后再试一次。
  • 如果你没有指定-W 1...会等多久?我在手册页中没有看到描述
  • 提供的 while 循环 (while ! ping -c 1 -W 1 1.2.3.4;) 在 Ubuntu 18 上对我不起作用...如果网络不可用,它将正确继续,但如果我得到有效的 ping,它也会继续结果。我不得不把它改成while ! (ping -c 1 -W 1 1.2.3.4 | grep -q 'statistics');