Remove a line from known hosts with single command

No more going into the file and deleting the entry manually.
To remove line 123 from ~/.ssh/known_hosts:

Usage

rmknownhost 123

Code
Put this it into a file called rmknownhost inside a folder that is in your PATH and chmod +x the file.

#! /usr/bin/env ruby
line = ARGV[0] || raise("gimme line to remove")
hosts = File.expand_path("~/.ssh/known_hosts")
content = File.readlines(hosts)
removed = content.delete_at line.to_i - 1
puts "Removed:\n#{removed}"
File.open(hosts, 'w'){|f| f.write content * ""}

4 thoughts on “Remove a line from known hosts with single command

  1. wow thats short 😀

    the “Removed: xxx” message is missing but thats not that important.
    Its a bit cryptic, wrapping it into a function would be good…

Leave a comment