Last active
May 26, 2023 02:17
-
-
Save ottosch/d9d7f66e16de8eb2a75ad7e4154d528c to your computer and use it in GitHub Desktop.
Shell script to set a static ip address in the systemd network unit. Needs sudo to write the file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env bash | |
if [ "$#" -eq "0" ]; then | |
echo "Usage: $0 <desired-ip-address>" | |
curr_ip="$(ip route get 1.1.1.1 | awk '{print$7}')" | |
echo "FYI your current IP address is: $curr_ip" | |
exit 1 | |
fi | |
# TODO: check if input looks like an ip | |
name=$(ip route get 1.1.1.1 | awk '{print$5}' | head -n1) | |
file="/etc/systemd/network/$name.network" | |
if [ -s "$file" ]; then | |
echo "File $file already exists. Check the file contents and delete it if not important" | |
exit 1 | |
fi | |
cat >"$file" <<EOF | |
[Match] | |
Name=$name | |
[Network] | |
Address=$1 | |
Gateway=$(ip route get 1.1.1.1 | awk '{print$3}' | head -n1) | |
DNS=8.8.8.8 | |
DNS=8.8.4.4 | |
EOF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment