Skip to content

Instantly share code, notes, and snippets.

@jk
Last active May 24, 2024 08:59
Show Gist options
  • Save jk/1bd8e08a6f390e0e43cf6a9bc7acd542 to your computer and use it in GitHub Desktop.
Save jk/1bd8e08a6f390e0e43cf6a9bc7acd542 to your computer and use it in GitHub Desktop.
Shell script to check syntax of /etc/hosts
#!/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