仅针对特定接口运行特定的 /etc/network/if-up.d-script

fra*_*dig 2 networking linux script network-interface

我想在通过调用启动特定接口(例如 eth0)时运行网络脚本

ifup eth0
Run Code Online (Sandbox Code Playgroud)

该脚本只能在启动 eth0 时运行。我的方法是编写脚本(名为script.sh)将其作为可执行文件放置在某处,然后写入/etc/network/interfaces

auto eth0
iface eth0 inet manual
up /path/to/script.sh
Run Code Online (Sandbox Code Playgroud)

有没有更优雅的方法来做到这一点?我可以/etc/network/if-up.d以某种方式使用脚本环境吗?据我所知,无论调出哪个界面,该文件夹中的所有脚本都将运行。

Zor*_*che 5

当调用 ifup.d 中的脚本时,会向其中传递大量与特定接口的配置相关的环境变量。例如,如果您的接口配置如下所示。

iface eth0 inet manual
  dofoo on
Run Code Online (Sandbox Code Playgroud)

然后您的脚本将收到一个变量,例如$IF_DOFOO值为on.

知道您可以在脚本的开头放置一些内容,例如

#!/bin/bash

if [ -z "$IF_DOFOO" ] ; then
    # this script only applies to interface flagged as dofoo
    exit 0
fi
... Doing the foo.
Run Code Online (Sandbox Code Playgroud)

完成后,该脚本可以轻松地放置在 if-up.d 下。

当然,您也可以简单地查看该$IFACE值,并将脚本硬编码为仅针对特定接口运行,或者将其与其他外部配置源相匹配。请参阅 中的其他脚本,if-up.d了解您可以执行的操作的一些示例。