Fix a terminal full of garbage after printing a binary file
Why letters turn into line-drawing symbols or typing stops echoing after you cat a binary file, and how reset, stty sane and Ctrl+O bring the terminal back.
A binary file is full of bytes that a terminal treats as commands. When you cat one, some of those bytes switch the terminal into another character set, turn off echo or change colors, and the session stays that way after the file ends.
Quick fix
Type this and press Enter, even if you cannot see what you type:
reset
reset puts the terminal modes back to sane values (echo on, normal line editing, newline translation, default special keys) and sends the terminal's reset sequence.
If Enter seems to do nothing, the terminal may no longer treat carriage return as end of line. Press Ctrl+J (line feed) instead: Ctrl+J, type reset, Ctrl+J.
What went wrong, and smaller fixes
There are two separate kinds of damage, and they have different fixes.
The display is wrong (letters show as line pieces, boxes or symbols). The byte 0x0E (Shift Out, Ctrl+N) switches the terminal to its second character set, which on VT-style terminals is usually line drawing. The byte 0x0F (Shift In, Ctrl+O) switches back. You can send it with:
printf '\017'
tput reset or reset also fixes this, along with stray colors and modes.
The line settings are wrong (no echo, Enter does not work, Ctrl+C does nothing). Those settings belong to the host's terminal driver, not to the terminal app. Restore them with:
stty sane
stty sane restores the host's line settings only. It does not send anything to the screen, so it will not fix scrambled characters.
If you are inside tmux, screen or Mosh
The garbage reached the program that draws your screen, not only your terminal. Run reset inside the pane first. In tmux, if the pane is still wrong, tmux respawn-pane -k restarts it (this ends the program running in it).
Avoiding it
- Check a file's type before printing it:
file name. - Look inside binaries with
less(it shows control bytes safely),hexdump -C name | lessorxxd name | less.
Related
- Clear the terminal screen and its scrollback
- Boxes show as q, x and lqqqk in a terminal
- Alternate screen, mouse and paste modes
- Escape sequences
- Do all terminals understand ANSI escape codes? TERM, terminfo and dumb terminals
- Pasted text shows ^[[200~ and ^[[201~: bracketed paste mode left on
Sources
- tset and reset manual page (ncurses)
- tput manual page (ncurses)
- stty manual page (GNU coreutils)
- tmux manual page (respawn-pane)
- less manual page (caret notation for control characters)
- console_codes manual page (SO and SI control characters)