Fix terminal after displaying a binary file

Often times when in a Unix/Linux terminal (Bash) for example you'll use the commands more or less or cat to view a file. When you do this and the file isn't meant to be viewed (such as /bin/ls) you'll get output like this:

                ss of binary output

What's going on here is that you just tried to view a file that's a program. An executable which aren't meant to be viewed with standard viewers as I mentioned above.

method #1 - reset

To fix this issue you can do the following:

  1. Hit Control + C a couple of times (Ctrl+C)
  2. Type the command reset and hit return

This should usually put your terminal back into a more normal mode. I'll mention one more thing, when you do the steps above, you'll by typing them blind into your terminal. So just make sure you're typing it correctly.

method #2 - stty sane

As suggested in the comments by @sendmoreinfo you might have better luck using the following commands instead if the above doesn't work:

$ stty sane
$ tput rs1

determining a files' type

Incidentally, if you come across a file and aren't sure if it's going to mess up your terminal you can inspect the file using the command file which will report back the type of file it is.

For example, with /bin/ls that file shows the following output:

$ file /bin/ls
/bin/ls: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.32, stripped

I've had an occasion where none of the usual tricks, reset or stty sane, worked (after accidentally calling print on a python bytearray). I had success with method 2 listed on this helpful blog.

I've since created a most helpful alias:

alias fix='echo -e "\033c"'

No single prior answer worked for me. But this seemed to do the trick in .bashrc add:

alias fix='reset; stty sane; tput rs1; clear; echo -e "\033c"'

and then when the problem occurs type this (even though you probably can't see it!)

(ctl-c, ctl-c, ctl-c)
fix

Much thanks to the prior submitters. Also, as a side note, the reason that your terminal goes wonky when showing those executable files (or keystores, etc) is that those files often contain binary sequences that are control codes. The control codes may do random things like switch to a graphics character set, set foreground and background colors to the same thing, etc.