Skip to content

Instantly share code, notes, and snippets.

@JeremyMorgan
Last active May 19, 2024 09:22
Show Gist options
  • Save JeremyMorgan/407cc551b1ba8a122a502c84044d4598 to your computer and use it in GitHub Desktop.
Save JeremyMorgan/407cc551b1ba8a122a502c84044d4598 to your computer and use it in GitHub Desktop.
List your interfaces, and IP (v4) addresses if they're available.
#!/bin/bash
# Define color codes
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m' # No Color
# Run the ip -c a command and process its output
ip -c a | awk -v green="$GREEN" -v red="$RED" -v nc="$NC" '
/^[0-9]+:/ {
# Print previous device if it had no IPv4 address
if (dev != "" && !has_ipv4) {
printf "%s: %sno IPv4 address%s\n", dev, red, nc
}
# Extract the device name and state
match($0, /<([^>]*)>/, state)
match($2, /([^:]+)/, device)
dev = device[1]
has_ipv4 = 0 # Reset IPv4 flag
if (state[1] ~ /UP/) {
dev_state = "UP"
} else if (state[1] ~ /DOWN/) {
dev_state = "DOWN"
} else {
dev_state = ""
}
}
/inet / {
# Extract the IPv4 address
match($2, /([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/, ip)
has_ipv4 = 1 # Set IPv4 flag
if (dev_state == "UP") {
printf "%s: %s%s%s\n", dev, green, ip[1], nc
} else if (dev_state == "DOWN") {
printf "%s: %sdown%s\n", dev, red, nc
} else {
print dev ": " ip[1]
}
}
END {
# Print the last device if it had no IPv4 address
if (dev != "" && !has_ipv4) {
printf "%s: %sno IPv4 address%s\n", dev, red, nc
}
}
'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment