diff --git a/Library/Homebrew/formula.rb b/Library/Homebrew/formula.rb
index cb27e949214c7612c974b180c54bee7ccea17170..5e8232d9723f4c509763ff6d4a453cc969a55b51 100644
--- a/Library/Homebrew/formula.rb
+++ b/Library/Homebrew/formula.rb
@@ -1521,7 +1521,12 @@ class Formula
   def eligible_kegs_for_cleanup
     eligible_for_cleanup = []
     if installed?
-      eligible_kegs = installed_kegs.select { |k| pkg_version > k.version }
+      eligible_kegs = if head? && (head_prefix = latest_head_prefix)
+        installed_kegs - [Keg.new(head_prefix)]
+      else
+        installed_kegs.select { |k| pkg_version > k.version }
+      end
+
       if eligible_kegs.any?
         eligible_kegs.each do |keg|
           if keg.linked?
diff --git a/Library/Homebrew/test/test_formula.rb b/Library/Homebrew/test/test_formula.rb
index c5175e27e6703f2dece565592a0bf097e1b84aa7..d586481f5be2aef8bd9efb8af4e78ee768b36d13 100644
--- a/Library/Homebrew/test/test_formula.rb
+++ b/Library/Homebrew/test/test_formula.rb
@@ -451,6 +451,30 @@ class FormulaTests < Homebrew::TestCase
     f3.rack.rmtree
   end
 
+  def test_eligible_kegs_for_cleanup_head_installed
+    f = formula do
+      version "0.1"
+      head "foo"
+    end
+
+    stable_prefix = f.installed_prefix
+    stable_prefix.mkpath
+
+    [["000000_1", 1], ["111111", 2], ["111111_1", 2]].each do |pkg_version_suffix, stamp|
+      prefix = f.prefix("HEAD-#{pkg_version_suffix}")
+      prefix.mkpath
+      tab = Tab.empty
+      tab.tabfile = prefix.join("INSTALL_RECEIPT.json")
+      tab.source_modified_time = stamp
+      tab.write
+    end
+
+    eligible_kegs = f.installed_kegs - [Keg.new(f.prefix("HEAD-111111_1"))]
+    assert_equal eligible_kegs, f.eligible_kegs_for_cleanup
+  ensure
+    f.rack.rmtree
+  end
+
   def test_pour_bottle
     f_false = formula("foo") do
       url "foo-1.0"