Skip to content

Instantly share code, notes, and snippets.

@jcanfield
Created January 15, 2015 21:13
Show Gist options
  • Save jcanfield/e336f3bfe9a657b7e90b to your computer and use it in GitHub Desktop.
Save jcanfield/e336f3bfe9a657b7e90b to your computer and use it in GitHub Desktop.
Flush DNS Cache on Mac OSX 10.10 Script (includes DNS Cache flush for OSX 10.9, OSX 10.7-10.8, OSX 10.5-10.6, Windows and Linux)
#!/bin/bash
## Restart Networking and flush current DNS cache
## Old command are commented out
## Original commands came from http://coolestguidesontheplanet.com/clear-the-local-dns-cache-in-osx/
##
## NOTE: mv -v $THIS ~/.bin/osx-dnsflush.sh
## sudo ln -sb $THIS /usr/local/sbin/osx-dnsflush
## USAGE: osx-dnsflush
# Clear cache for Mac OSX 10.10
echo "Clearing DNS Cache..."
read -p "[Press Enter To Continue]"
sudo discoveryutil udnsflushcaches
# Mac OSX 10.9
# dscacheutil -flushcache; sudo killall -HUP mDNSResponder
# Mac OSX 10.7 – 10.8
# sudo killall -HUP mDNSResponder
# Mad OSX 10.5 – 10.6
# sudo dscacheutil -flushcache
# Windows cmd.exe
# ipconfig /flushdns
# Linux (common Debian variant)
# /etc/init.d/named restart
# /etc/init.d/nscd restart
echo "DNS Cache cleared..."
exit
@pythonmagic
Copy link

you could use below code snippet idea to make it work for all OSX version.

MAJOR_MAC_VERSION=$(sw_vers -productVersion | awk -F '.' '{print $2}')
if [ "$MAJOR_MAC_VERSION" -ge "10" ]
then
sudo killall -HUP mDNSResponder
else
sudo dscacheutil -flushcache
fi

if you want to make it even work on Linux then you could add

if [ "$OS" = "Darwin" ]
then
MAJOR_MAC_VERSION=$(sw_vers -productVersion | awk -F '.' '{print $2}')
if [ "$MAJOR_MAC_VERSION" -ge "10" ]
then
sudo killall -HUP mDNSResponder
else
sudo dscacheutil -flushcache
fi
fi

if [ "$OS" = "Linux" ]
then
	# Find Unix version and cleares the DNS Cache
	MAJOR_UNIX_NAME=$(lsb_release -i | awk -F ":" '{print $2}')
	if [ "$MAJOR_UNIX_NAME" = "Ubuntu" ]
	then
		sudo /etc/rc.d/init.d/nscd restart
	fi
fi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment