Last active
May 24, 2024 08:59
-
-
Save jk/1bd8e08a6f390e0e43cf6a9bc7acd542 to your computer and use it in GitHub Desktop.
Shell script to check syntax of /etc/hosts
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
#!/bin/zsh | |
# Function to validate each line of /etc/hosts | |
validate_line() { | |
local line="$1" | |
# Regular expression to match valid IP address and hostname entries, including comments | |
if [[ "$line" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}([[:space:]]+([a-zA-Z0-9.-]+,?)+)+$ ]] || [[ "$line" =~ ^::1([[:space:]]+([a-zA-Z0-9.-]+,?)+)+$ ]] || [[ "$line" =~ ^#.* ]]; then | |
echo "Valid: $line" | |
else | |
echo "Invalid: $line" | |
fi | |
} | |
# Read /etc/hosts line by line | |
while IFS= read -r line; do | |
validate_line "$line" | |
done < /etc/hosts |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment