2025-08-08

how to configure an on-demand bridge interface on linux

this example uses systemd-network and two scripts, start-bridge and stop-bridge, to create and remove a bridge interface on demand.

this can be used, for example, for networking in qemu or virtualbox virtual machines.

configuration

/etc/systemd/network/inactive/enp5s0-static.network

[Match]
Name=enp5s0

[Network]
Address=192.168.178.24/24
Gateway=192.168.178.1
DNS=fd1e:d35:c896::2e91:abff:fe95:3f0
IPv6AcceptRA=yes

/etc/systemd/network/enp5s0-bridge.network

[Match]
Name=enp5s0

[Network]
Bridge=br0

/etc/systemd/network/br0.netdev

[NetDev]
Name=br0
Kind=bridge
MACAddress=b4:2e:99:95:9a:1e

/etc/systemd/network/br0.network

[Match]
Name=br0

[Network]
DHCP=yes
DNS=8.8.4.4

scripts

start-bridge

#!/bin/sh

conf_dir="/etc/systemd/network"
inactive_dir="$conf_dir/inactive"

default="$conf_dir/enp5s0.network"
static_backup="$inactive_dir/enp5s0-static.network"
bridge="$inactive_dir/enp5s0-bridge.network"
active_bridge="$conf_dir/enp5s0-bridge.network"

# move default config to inactive if it exists and backup is not yet there
if test -e "$default" && test ! -e "$static_backup"; then
  mv "$default" "$static_backup"
fi

# move bridge config to active if not already there
if test -e "$bridge" && test ! -e "$active_bridge"; then
  mv "$bridge" "$active_bridge"
fi

systemctl restart systemd-networkd

stop-bridge

#!/bin/sh

conf_dir="/etc/systemd/network"
inactive_dir="$conf_dir/inactive"

default="$conf_dir/enp5s0.network"
static_backup="$inactive_dir/enp5s0-static.network"
active_bridge="$conf_dir/enp5s0-bridge.network"
bridge_backup="$inactive_dir/enp5s0-bridge.network"

# move bridge config back to inactive
if test -e "$active_bridge" && test ! -e "$bridge_backup"; then
  mv "$active_bridge" "$bridge_backup"
fi

# restore static config if backup exists and not already present
if test -e "$static_backup" && test ! -e "$default"; then
  mv "$static_backup" "$default"
fi

systemctl restart systemd-networkd

# fully remove bridge interface
if ip link show br0 >/dev/null 2>&1; then
  ip link set enp5s0 nomaster 2>/dev/null
  ip link set br0 down
  ip link delete br0 type bridge
fi