July 29, 2020

~terminal control codes~

So terminals have some fancy control codes, commonly used for things like changing text colours or managing the cursor and buffer size, but it turns out some control codes exist to play with things slightly outside of the terminal itself.

swapping window focus with control codes

As it turns out on Mac OS, the default Terminal.app (but not iTerm2) supports some of these fancier control codes that allow things like switching window focus or minimizing the terminal

If you enter echo -ne "\x1b\x5b2t", your terminal window will minimize (or “iconify”), and if you enter echo -ne "\x1b\x5b6t", focus will move to the previously focused window (technically the terminal is “moved to the bottom of the window stack”).

Since these are just control codes that take action when printed to the terminal, you can also ‘run’ them by cating a file, or curling a page, such as curl https://polynomial.space/minimize.txt

Some other silly examples:

# Rapidly swap focus between windows (seen in gif above)
for i in 5 6 5 6 5 6 5 6 5 6 5 6 5 6 5 6 5; do echo -n "\x1b\x5b${i}t"; sleep 0.1; done

# Grow the window gradually
for i in $(seq 24 48); do echo -n "\x1b\x5b8;${i};80t"; sleep 0.05; done

# Minimize and unminimize window ("iconify and de-iconify")
echo -ne "\x1b\x5b2t"; sleep 1; echo -ne "\x1b\x5b1t