Terminal – Why Does ‘head /bin/ls’ Reset the Terminal?

binaryterminal

If you do something silly like cat /var/log/wtmp your terminal can get messed up as shown in the screenshot. I know there are a number of ways of fixing this. One of the ways not mentioned on that post, which I was told about years ago is to run the command highlighted in a red box in the screenshot.

head /bin/ls

This works.

Why?

Terminal Reset Screenshot

Best Answer

Terminals are controlled by escape sequences that are sent in-line with the character data to be displayed. That is how, for example, echo -e '\e[34m' will turn the text on many terminals blue. It's echoing some characters to the terminal—they happen to be an escape sequence which sets the foreground color.

The terminal was messed up by being instructed to switch into some alternative character set (and possibly a bunch more things). It did that because /var/log/wtmp happened to contain the escape sequences used to switch character sets. Technically, it's not really messed up—it's operating exactly as it is designed to. (Try tput smacs to mess up your terminal on demand; tput rmacs to change that parameter back.)

reset, etc. function by sending escape sequences resetting various parameters to their defaults. That "fixed" the terminal.

That head /bin/ls trick is working because your /bin/ls (or at least the portion printed by head) happens to contain an escape sequence changing the terminal parameters back. That's not at all portable—it doesn't work here for example—and likely does a much less thorough job resetting defaults than reset, etc.)

Related Question