Skip to content

Instantly share code, notes, and snippets.

@x512
Created November 29, 2024 12:33
Show Gist options
  • Select an option

  • Save x512/fd10a221955219ac887e762a24f67b1b to your computer and use it in GitHub Desktop.

Select an option

Save x512/fd10a221955219ac887e762a24f67b1b to your computer and use it in GitHub Desktop.
Basic shellscript to convert a country name to an ISO code
#!/bin/bash
#
# Input:
# $1 = Country name
# Example:
# sudo ./getiso.sh China
# Output:
# cn
# Check if the required permissions are met
if [[ "$EUID" -ne 0 ]]; then
echo "Error: this script must be run as root. Please try again with sudo."
exit 1
fi
# Check that dependencies are installed
if ! command -v whois > /dev/null 2>&1; then
echo "Error: whois command not found. Please install whois and try again."
exit 1
fi
# Function to convert a country name or ISO code to an ISO code
get_iso_code() {
local country=$1
# Check if the input is a valid ISO code
if [[ "$country" =~ ^[A-Z]{2}$ ]]; then
echo "$country"
return
fi
# Lookup the ISO code using the whois command
iso_code=$(whois -h whois.iana.org "=$country" | grep "^country" | awk '{print $2}' | tr '[:upper:]' '[:lower:]')
if [[ -z "$iso_code" ]]; then
echo "Error: invalid country name or ISO code. Please enter a valid country name or ISO code and try again."
exit 1
fi
echo "$iso_code"
}
# Process the command line argument
if [[ $# -ne 1 ]]; then
echo "Error: invalid number of arguments. Please enter a country name or ISO code and try again."
exit 1
fi
country=$1
# Convert the country name or ISO code to an ISO code
iso_code=$(get_iso_code "$country")
echo "$iso_code"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment