Skip to content

Instantly share code, notes, and snippets.

@norandom
Last active February 16, 2024 09:59
Show Gist options
  • Save norandom/0a76de6642c6e86e74c82fe48934dfbb to your computer and use it in GitHub Desktop.
Save norandom/0a76de6642c6e86e74c82fe48934dfbb to your computer and use it in GitHub Desktop.
Persist DHCP provisioned IP config (Arch, systemd-networkd)
#!/bin/bash
# Interface name, e.g., enp1s0
IFACE="enp1s0"
# Ensure systemd-networkd is enabled
systemctl enable systemd-networkd
systemctl start systemd-networkd
systemctl start systemd-resolved
systemctl enable systemd-resolved
# Get current IP, subnet mask (in CIDR notation), and gateway
IP=$(ip -4 addr show $IFACE | grep -oP '(?<=inet\s)\d+(\.\d+){3}/\d+')
GATEWAY=$(ip route | grep default | awk '/default/ { print $3 }')
DNS=$(awk '/^nameserver/ {print $2}' /etc/resolv.conf | tr '\n' ' ')
# Directory where systemd-networkd configurations are stored
NETWORKD_CONF_DIR="/etc/systemd/network"
# Create or overwrite the .network file for the interface
cat <<EOT > $NETWORKD_CONF_DIR/10-$IFACE.network
[Match]
Name=$IFACE
[Network]
Address=$IP
Gateway=$GATEWAY
DNS=$DNS
EOT
# Restart systemd-networkd to apply changes
systemctl restart systemd-networkd
echo "Static IP configuration for $IFACE is complete."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment