Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Script for logging IP address changes. Checked with shfmt: `docker run --rm -it -v "$PWD":/src peterdavehello/shfmt shfmt -i 2 -w /src/ip-address-log.sh`
#! /usr/bin/env bash
# Stop on errors, unset vars and broken pipes
set -o errexit
set -o nounset
set -o pipefail
LOG_FILE=${1:-}
if [ -z "$LOG_FILE" ]; then
echo "Please provide a logfile as the first argument"
exit 1
fi
CURRENT_IP=$(curl -s ifconfig.me)
LOG_IP=$(date "+%Y-%m-%dT%H:%M:%S%z")"\t$CURRENT_IP"
if [ ! -f "$1" ]; then
# Log file doesn't exist yet, create the file
echo "Creating $LOG_FILE and logging IP address..."
echo -e $LOG_IP >"$LOG_FILE"
else
# Log file exists, check last entry
PREV_IP=$(tail -n1 $LOG_FILE | cut -f 2)
if [ "$PREV_IP" != "$CURRENT_IP" ]; then
echo "New IP, logging to $LOG_FILE..."
echo -e "$LOG_IP" >>"$LOG_FILE"
else
echo "IP Address is unchanged"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment