Hacker News new | past | comments | ask | show | jobs | submit login
Clear Your Terminal in Style (adammusciano.com)
290 points by signa11 on March 5, 2020 | hide | past | favorite | 130 comments

I’d just settle for macOS’ Terminal.app’s ⌘-K, that resets the terminal, and clears all the screen including scroll back window. Something so basic I have it in muscle memory but I haven’t found the equivalent in Linux terminals.

A lot of people swear by stuff like iTerm2, but I'm almost a little ashamed to admit that even though I have iTerm configured to my taste, I often still reach for macOS' native terminal. It's not gloriously beautiful or anything (basic Zsh with powerline for the shell), but it just seems to work great without the frills.

Little shortcuts that think of stuff like this without any configuration (iTerms is impressively extensive) are just a cherry on top. It kind of bums me out that's not linux native. Do you know of any other useful shortcuts specific to macOS? I've been using ctrl+L for the longest time. Thank you for sharing!

> A lot of people swear by stuff like iTerm2

Actually, I've been using Terminal for years. I usually try to use default apps as much as possible (Safari, Mail, Notes, Terminal) to reduce configuration overhead. I switched to iTerm2 a few days ago after reading an article on HN... not sure if it worth the change, but haven't tried anything fancy yet. What would be the killer feature of iTerm2?

Drop down with global shortcut (I use control + ‘)


For me it is its integration with tmux, and therefore being able to use the command line in a remote computer as if you were using it locally.

I just use tramp for this.

I use profile triggers to change the color scheme of the shell when I SSH to a production server. The color I chose is different from my regular scheme so that it reminds me I am in production and things can break if I'm not careful.

I'm sort of in the opposite camp — I remember there being a non-trivial reason for moving over to iTerm several years ago, but now it's just become a habit and I can't for the life of me remember why I'm using it still.

As for shortcuts — ctrl-K (kill line), ctrl-A (go to start of line), ctrl-E (end of line) are my bread and butter, and work with most shells.

One thing I loved about Macs, even though I haven't used one in years, was that you could use Emacs keybindings with the control key and "standard" keybindings with the command key. Being able to type both C-c and ⌘-c was nice.

Definitely, having readline shortcuts available more or less across the whole OS is a godsend.

Since cmd+<number> now switches tab in Terminal.app, and the other few things I like, such as remembering the scrollbacks, number of tabs and cwd's, I find I have no use of iTerm2 any longer.

Plus, Terminal.app feels much faster. Using terminal Emacs feels very different in the two terminals.

Plus, Terminal.app feels much faster. Using terminal Emacs feels very different in the two terminals.

I recently switched back to Terminal from iTerm, and was amazed by the speed increase.

When entering commands, it is visibly a little "snappier." But where it really shines is in the output.

I have a few of batch processes that I have to run once a week, and they're all pretty heavy on the debug output, with lots of VT100 eye candy. One process that used to take close to six hours in iTerm got significantly shaved when I switched to Terminal.

Since I only run this once a week, I haven't had a chance to benchmark it, but my guess is that Terminal shaved 40 minutes off the job.

The only thing I miss from iTerm is having two sessions open in a single window. I suspect this is possible in Terminal, but I haven't figured it out yet. When I click the "Split Pane" button, I get two panes of the same session, instead of a new session in the new pane.

The fact that Ternimal.app and iTerm2 use different keyboard shortcuts for clearing scrollback buffer (⌥⌘K vs ⇧⌘K) is a constant frustration of my spotty use of Terminal.app. I would instinctively hit the iTerm2 shortcut, which brings up a connect to server panel or something.

You can use System Preferences (Keyboard -> Shortcuts, “App Shortcuts” in the list) to change any binding in any menu item in any app. In this case you could force both apps to use the same keys for those commands.

Good point. I used that feature in the past but somehow haven’t touched it in years.

> The fact that Ternimal.app

That typo has a nice program of its own: https://github.com/p-e-w/ternimal

I don’t even install any other terminal. I just update bash to latest and stick to stock terminal. I have come to believe that often tool overload adds to the clutter and complexity and problems that didn’t need solving in the first place.

I am currently using Fedora 31 Cinnamon which uses GNOME Terminal and the shortcut to reset and clear screen/scrollback is CTRL+L. I am not sure if this shortcut is standard on GNOME Terminal or not, but it's present in this flavor.

EDIT: On my windows machine I think it is ALT+F8 in Git Bash. May be similar in other terminal emulators.

CTRL-l is a standard "clear the screen" keystroke, and should work in all terminals, but it does not necessarily clear the scrollback buffer. Since "scrollback" is something implemented by the emulator itself, you'll have to look up how to do it there.

I use konsole, and it's CTRL-SHIFT-k there by default, I believe. I just ran gnome-terminal, and I see in Edit -> Preferences -> Terminal -> Reset and Clear that you can give it a shortcut key but it does not appear to ship with one configured by default.

The reset command should clear the scrollback buffer. On older terminals where you'd get a garbled screen if you accidentally cat a binary file, it will give you your ASCII back.

Trying it just now on konsole, it does not. Whether that's because your terminal is following standards or because your terminal is interpreting a terminal command that doesn't actually say anything about scrollback to also clear scrollback, I don't know, and await anyone who does to answer that question.

My gut is that the terminal protocol would know nothing about scrollback and thus not have a "clear scrollback" command in it directly. There are plenty of other indications that scrollback is basically a hack.

[Konsole] Settings -> Configure Keyboard Shortcuts ... "Clear Scrollback and Reset". On my Arch boxes it is mapped to Ctrl + Shift + k. That's probably a default from upstream.

Tried it on konsole 19.12.2 (on Arch), it works for me.

Your "gut" is wrong. It's ED 3.

It's a common feature, but not formally standardized.

ED 3 isn't actually in the [ECMA-048] spec.

It was an xterm feature introduced in June 1999. Several terminal developers later adopted the feature. In April 2011, a Red Hat developer submitted a patch to the Linux kernel, modifying its console driver to do the same thing.

So it's not a formal standard, but it's universal on Linux since 3.0 and many terminal emulators have adopted it.

This history is covered in [clear(1)] from the ncurses project.

[ECMA-48]: http://www.ecma-international.org/publications/files/ECMA-ST...

[clear(1)]: http://man7.org/linux/man-pages/man1/clear.1.html#HISTORY

EDIT: Fix wording and formatting.

... none of which contradicts the point that the protocol does know about scrollback. The aforementioned developer, Petr Písař, got the implementation wrong, note.

* https://unix.stackexchange.com/a/375784/5132

* http://jdebp.uk./Softwares/nosh/guide/commands/setterm.xml

Reset takes at least a couple seconds though, I’m not sure I’d swap it with clear in something like:

    clear && make test

I may have changed the key binding after installation. It has been a while so it feels like it has always been that way.

It's actually an Emacs keybinding, that was added to GNU readline, which is used by Bash; most shells followed suit (either by using readline, or implementing it themselves).

Ctrl + l is in Bash, in your case.

While many of the readline keybindings come from Emacs, I would have said the common shell handling of Ctrl-L comes from that ^L is ASCII form-feed, which is "clear the page; start a new page" (in the same way that ^H is ASCII backspace).

I hadn't considered Bash C-L to be the same as Emacs C-L, since in Emacs I can hit C-L again to "undo" it (kinda).

C-l doesn't clear anything in it's default behavior right? It changes the line-at-poit to be at the center of the screen, bottom, or top, depending on how often yoi press it.

I would never have associated that with screen clear.

E: excuse me, of course C-l does the same scrolling in the terminal, it doesn't clear the history of course.

It's also super helpful when you want to run one command which spews out a bunch of errors, and then read the first error. Cmd-K, enter, and fling up the the trackpad. I think I'd have to pipe to less if I don't have cmd-K.

Cmd up and down navigates between prompts, so you don’t even have to scroll

I tried this and it even worked within the sqlite3 session I have open, very nice.

This changes everything!

printf "\033c"? I don't know if it resets, but it does clear the scroll buffer. I use it before compiling (printf "\033c"; make) so that I don't have to search for the first error or warning, I can just scroll all the way up.

Can substitute a forward slash for the 0 and remove the quotes

   printf \\33c
Another way is to use a program that converts hex to binary. A short script to use when there is no clear, tput, etc, e.g., xxd or nc-data

   exec echo 1b63 |exec xxd -p -r

   echo -e '27\n99\n' |exec nc-data -g

   exec echo |exec sed '1i\
   27 \

   ' |exec nc-data -g

\ is a backslash

/ is a forward slash, a.k.a. simply “slash”

Not sure why I always get this wrong. Maybe it is because when I draw these characters on a surface, I start from the top not the bottom. Hence the line goes forward for a "backslash" and backward for a "forward slash". What is the etymology of these terms?

Probably better to just use "escape" for backslash and "slash" for forward slash.

As I said elsewhere in this discussion, use DECSTR instead of RIS unless you really need all of the things that RIS does to actual terminals, like performing selftests and resetting the serial connection. Habitual use of RIS is a bad habit to get into.

On iTerm, that clears everything visible on the screen, but not the scroll history.

Sounds like your terminal clears everything? vt100 variants are a, uh, delightful mix of nearly-compatible dialects...

KDE's Konsole has it at CTRL+ALT+K by default.

The command "tput clear" should work everywhere though. And frankly, while obviously more work than a keyboard shortcut, it's not that much of an effort.

Use clear and the flush_scrollback escape:

  $ clear; printf '\e[3J'
(edit: whoops wrong URL, sorry https://apple.stackexchange.com/a/113168 )


I use this too but on linux, I am constantly hitting cmd-k and control-l in a sort of futile attempt to reset the screen correctly.

I think this needs a solution -- a keymapping and a function that resets the terminal need to be consciously united.

actually, I think I need a full set of keystrokes for linux. Somehow on ubuntu pressing the command key leads to all the windows rearranging like expose on mac.


You can make your life easier on macOS by aliasing the `⌘-K` shortcut, as in: https://github.com/kdeldycke/dotfiles/blob/23ac0cd2a6c944242...

When I switched from macOS to Linux, not having ⌘-K really bugged me.

However I found out that most terminal emus on Linux also have this feature as Ctrl-L.

In gnome-terminal you have to press Ctrl-K to clear the screen, and then Ctrl-L to redraw the prompt.

The bash manual documents Ctrl-L as "Clear the screen leaving the current line at the top of the screen."

Is it possible to bring it back? I’ve pressed it accidentally on server window and lost the whole svr output ( I know I could look at logs but it would still be nice to quickly bring back stdout)

Whoa, someone downstream says `reset` clears scrollback.

Konsole has that since forever.

You don't know ctrl+L?

It looks like you're getting downvoted without explanation: Ctrl+L doesn't clear the scrollback, it just scrolls the terminal down.

Alacritty clears with Ctrl-L, out-of-the-box.

Also, from `man bash`...

> clear-screen (C-l) Clear the screen leaving the current line at the top of the screen. With an argument, refresh the current line without clearing the screen.

Also, Terminal.app seems to implement almost as many extensions as XTerm, and does them pretty well.

It's too bad it's so slow though (in terms of throughput, that is; latency is pretty okay).

The square brackets for arithmetic conditionals in bash are deprecated. Rather than:

    [ $[$RANDOM % 10] = 0 ]
...you can use double-parentheses. Therein, you can omit the `$` on variables and, remember, the expression evaluates to true for any non-zero value. Thus, instead:

    (( RANDOM % 10 ))

$[...] also establishes an arithmetic context, so

  $[RANDOM % 10]
works fine – but you're right, $[...] is not even mentioned in the manual any longer. The release notes[1] say that it's "no longer supported" in the changes for Bash 2.0 (that's 1996!), and Chet Ramey talks about it in the bug-bash mailing list[2].

[1]: http://tiswww.case.edu/php/chet/bash/NEWS

[2]: https://lists.gnu.org/archive/html/bug-bash/2012-04/msg00034...

You changed the probability here from 10% to 90% by inverting the test.

True, you can just invert: alias clear='if ! (( RANDOM % 10 )); then timeout 3 cmatrix; clear; else clear; fi'

((RANDOM % 10)) || timeout 3 cmatrix ; clear

This perfectly illustrates why I never bothered to learn bash syntax, and always just google for examples.

It may not be stylish, but I was very happy when I realised that CTRL+L will clear the screen, decent speed up if you're doing a load of demos and want the cursor at the top of the terminal

Unfortunately, Emacs uses CTRL+L to scroll the text buffer so that the caret is in the center. This collision means I often clear terminals by accident.

All the more reason for you to finally bite the bullet and make the switch to the superior editor /s

... where Control+L means repeat previous find/replace. (-:

It's not every day that you see someone abandoning Emacs for nano.

It does a cycle in Emacs, actually. First it centers, then it puts the caret at the bottom, then it puts it an the top (like readline, in a way)

Yes (actually, it's center -> top -> bottom); I just didn't want to make the comment longer. Anyway, in Emacs, it's something I frequently do without thinking.

Any kind of delay will turn into an annoyance.

If it doesn't, then the randomness will make it a dopamine hit / that somehow makes your brain feel rewarded. Which will lead to more terminal clearing. Not sure if that's the thing you want :-)

I'd stick with CTRL+L instead.

That's what I thought too. It looks cute, but I normally turn down any animation delays I can. After the first dozen times it just becomes annoying.

ahhh missing a great effect



I think an ideal clearing style would have the resulting shell prompt as an element of the animation. Let's say you've get the matrix digital rain, which resolves into just the prompt "raining" and then resolving into the regular text. Or just the prompt easing/fading in after the main loop.

But yes, most of the animations are quite a bit too long. I wouldn't mind a quick Star Wars diagonal wipe, though, to be honest.

What's wrong with control L? That's been the standard way since the 80s at least.

Cool tool, but as someone who actually works in the terminal, I would hate this after one use. Maybe alias it to `explody_clear` for fun use every once in a while.

If I want the terminal cleared, I want it cleared immediately so that I can go about my next task, or wipe sensitive data from my screen. Adding a delay to the task will annoy me immediately.

I've just used alias c=clear in my .bashrc and never looked back. Not even Ctrl+L feels as convenient as c+Enter

the full monty: alias c='echo -e "\033c" ; stty sane; setterm -reset; reset; tput reset; clear'

doesn't only clear the screen, but also escape any "broken" terminal configuration such as output of a binary on the tty

One can spot cargo cult command-line use when two pairs of the commands overlap functionally, and another triplet is the same program by different names.

Also note that RIS is a bad idea, discouraged since 1983 I recently discovered, although DEC did not think to tell people outside DEC this for half a decade. Use DECSTR.

setterm does not work on macOS. I find reset(1) working fine. It already does clear, too.

One of these days, someone will take my portable setterm, which compiles fine on FreeBSD, and compile it on MacOS. (-:

* http://jdebp.uk./Softwares/nosh/guide/commands/setterm.xml

> Ctrl+L feels as convenient as c+Enter

I learned to hit Ctrl with my palms, and never looked back. Do you use your pinky? If so, I agree c+Enter is more convenient than ctrl+L.

It never even occurred to me to do that but trying it now, I don't think it's feasible for my hands. Either my palm mashes CTRL, ALT, and CMD (and sometimes FN and Shift) or I have a super awkward angle to get to the C key. It seems much easier to just drop my pinky down for half a second.

EDIT: After a suggestion from another user, I just remapped my Caps Lock to CTRL. That seems a lot easier to deal with. I'll try that for a bit and see how it goes.

I use my left pinky to press Ctrl, and I use the right hand for L (index finger), so it makes no difference whether I press L or Enter using my right hand. I would probably use the right pinky for the Enter key. Works either way to me, but I am used to pressing Ctrl-L (left pinky for Ctrl, right index finger for L).

I have mapped capslock to ctrl (esc if used without modifiers) which made ctrl+L extremely comfortable for me.

I don’t quite understand why. With one hand or two?

Left pinky for ctrl (capslock) and right ring finger for L. Works incredibly well for my hands (a quality keyboard helps too). The capslock mapping is obviously meant for vim but works great for many shortcuts like this (ideally there would be a second ctrl/esc and other modifiers to operate with right pinky comfortably, starting my first custom build soon...).

Now you have Ctrl on home row, instead of two rows down.

On a standard PC keyboard, I just use my palm to hit Ctrl (part of why I detest keyboards where Left Ctrl is not at the bottom left corner.

Some smaller keyboards (including laptops) make the control key small or add an "Fn" key to the bottom-left corner (Apple does this). I tend to hit Ctrl with my left hand, so mapping caps lock to Ctrl makes it more reliable to hit.

Ctrl+L works when a program is running. Clear does not.

> Ctrl+L works when a program is running. Clear does not.

I can't see how because ctrl+l is a $SHELL / readline shortcut rather than one defined in the terminal emulator. Once you run a program you're forking STDIN control to another process so you'd have to wait for the $SHELL / readline prompt again just like you would if you typed a command / function / alias into the command prompt.

Is ctrl+c handled; by the terminal emulator?

ctrl+l allows to clear when the prompt is non-empty, maybe parent poster meant that

I'm not 100% sure how ctrl+c (and ctrl+z) are handled but I do know they're edge cases because they're managed by the kernel and are not re-definable.

The terminal can optionally catch some characters and convert them to signals. By default, ^C sends SIGINT, ^\ sends SIGQUIT, and ^Z sends SIGTSTP. Programs can disable that for their own purposes (stty -isig) and you can rebind them to other characters if you want (stty intr, stty quit, stty susp) but I don't know why anyone would these days.

In Linux and UNIX you enable or disable use of ctrl+c (effectively setting the tty into a raw mode) via syscalls against the tty file descriptor - it is not handled by the terminal emulator at all (in fact if you read the man page for `stty` you'd see it's changing the your terminals fd and not the terminal emulator).

Sure, theoretically terminal emulators could capture and even rebind those keys via the APIs of whatever graphical toolkit they're built in....but if you wanted to rebind SIGINT to another key in the terminal emulator, that terminal emulator would still have to transmit ^c to the tty.

As for rebinding those keys in the kernel, Linux simply doesn't support doing that and nor does it support binding other keys to different signals. In fact I've tried to do this on a tool I was working on to emulate BSD's SIGINFO in Linux (turned out not to be possible) as as well part of the job control (SIGSTSP et al) support in my $SHELL (https://github.com/lmorg/murex).

This is also why you can throw signals over an SSH (or other remote shell) session when the terminal emulator itself would have no knowledge of the commands running on the remote host.

Good point, I should have said TTY driver (all my information is from half-remembered reading of https://www.linusakesson.net/programming/tty/index.php, any mistakes are my own).

With respect to rebinding, what is "stty intr ^D" doing if not rebinding the interrupt character to ^D?

I feel your pain about not having SIGINFO though.

I hate sl. I always alias it and I will purge it from any system that I am in charge of. It is not fun nor cute and I do not want to waste my time watching it.

If you use a Dvorak keyboard layout, you will be immune to sl, without having to set any alias.

In an average day I open more than 100 terminal windows (alt-escape which opens rxvt-unicode). Use most briefly, then they vanish behind other windows.

Every-so-often, when I get in a mess with alt-tab I run killUnusedTerminalsAndBC.sh, which kills the dozen or so bc instances that accumulate, and then kills any terminals which don't have anything running in them. I've done that a couple of times today, just did it again and killed another 10 hanging around. Most of the rest are idle, but sshed to other servers, so they don't get reaped.

I use yakuake with a persistent tmux session for that, I just open my yakuake terminal and perform whatever I want in a new tmux pane (or window if preferred).

My new favourite way: ttyfire


Video is of it running in gnome-terminal, where the terminal window is scaled right down with ctrl-minus.

Source is here: https://github.com/dmo9000/ttyfire

So far its been able to run on Linux, FreeBSD, Solaris and OpenBSD with minor patches. NetBSD xterm doesn't seem to support Unicode for some reason.

This was inspired by the Javascript DOOM fire effect that was posted here a bit over a year ago.


I like the VT100 demo. I wonder if there are demos for the more advanced color VT340 terminals?

They actually aren't VT100 demos, if you look at them. Several of them use SGR control sequences to set colour. I suspect that quite a few of them would not have worked on an actual VT100 series terminal.

I guess it is to late and nobody will read this. But anyway.

A couple of years ago i bought a new old stock DEC VT340 terminal, complete with a set of manuals. It can do much more than ANSI. Wikipedia says it can to bitmap and vector graphics "ReGIS, Sixel and Tektronix 4010". I wonder if there are scripts or tools to demo those capabilities.

ANSI demos would be similar to your request, but use a different character set (IBM PC's default character mode--code page 437).

I guess it is to late and nobody will read this. But anyway.

A couple of years ago i bought a new old stock DEC VT340 terminal, complete with a set of manuals. It can do much more than ANSI. Wikipedia says it can to bitmap and vector graphics "ReGIS, Sixel and Tektronix 4010". I wonder if there are scripts or tools to demo those capabilities.

I wonder if the train animation is a direct descendant of this program which was published by Processor Technology in their Access newsletter, Volume 1, No. 4. The author is "Newett Awl", which supposedly was the pseudonym of Gordon French, co-founder of the Homebrew Computer Club.

PT was the maker of the Sol-20, a 1976-ish CP/M machine.

demo: https://www.youtube.com/watch?v=UjiYQqTWHbo

Source code: http://sol20.org/programs/train.asm

What would you think of a command that clears the screen but first pushes the contents onto a stack so you could return to it later? The thought crosses my mind once in a while but I wonder if I’m the only one who wants it.

That's just a form feed character, or CTRL+L.

In times past, Solaris' /usr/bin/clear was a sh script which ran "tput clear", but the amusing parts was the notice which includes

  # Copyright (c) 1987, 1988 Microsoft Corporation
  # All Rights Reserved
  # This Module contains Proprietary Information of Microsoft
  # Corporation and should be treated as Confidential.

Does anyone have any idea why the download to the viewer needed for the Twilight Zone file gets flagged by Firefox as a virus? I can't see anything strange in it.


While I was working on Alacritty's `clear` handling, I stumbled on a number of interesting details (including a recently fixed bug in `clear` itself).


Another list of terminal pretties missing lolcat.

I’d like the matrix animation with lolcat pretty pls.

It works: `cmatrix | lolcat`

I don't think there's a way to map these cute animations to Ctrl+L is there?

> [ $[$RANDOM % 10] = 0 ] && do_this || do_that

> This gives roughly a 1 in 10 chance of do_this running, and a 9 in 10 chance of do_that running.

`do_that` having a 9 in 10 chance depends on `do_this` having a 0 chance of returning a falsy status.

Afaik this is common syntax for if/else based only on the the initial condition; I can't remember where it's documented but I think it requires the do_this part to be a single expression. However, bash pitfalls recommends against using && and || except for very basic logic.

> Afaik this is common syntax for if/else based only on the the initial condition

You're right that it's common, but you're wrong saying that it's based only on the initial condition:

  $ true && cat nonexistent.txt || echo "shouldn't have run"
  cat: nonexistent.txt: No such file or directory
  should't have run
> I can't remember where it's documented but I think it requires the do_this part to be a single expression

It's not documented like you said because it's a hack. &&/|| aren't meant to simulate if/else. These aren't expressions either. And they aren't really limited either:

  $ true && { echo "true condition ran"; cat nonexistent.txt; } || echo "false condition ran"
  true condition ran
  cat: nonexistent.txt: No such file or directory
  false condition ran
> However, bash pitfalls recommends against using && and || except for very basic logic.

The fact that people end up thinking that it's an ok substitute for if/else syntax is the reason why it's recommended against.

This one should really have a massive "do not try this":

[ $[$RANDOM % 6] = 0 ] && sudo rm -rf / || echo "Not today"

An awful lot of people just copy and paste things to see what'll happen.

I don't think it does. If one blindly copies a command to their terminal, this is a good lesson not to do so. Too many projects suggest `curl foo | sh` as the "quick and ready to go" method for installation which is equally as bad as rm -rf in the wild.

83% of them wouldn’t see any effect.

Unfortunately that might just compel them to keep trying.

I agree. However, in this case I believe most versions of rm would complain about passing "/" as an argument without also passing "--no-preserve-root", so there's that at least.

I‘m not sure if I need an animation for clearing the terminal, but I enjoy having the ruby gem gti providing an animation and executing the respective command whenever I mistype git.

Unrelated that some may find useful- type reset to actually clear scrollback too if you're confused after too much output

Wow - if you go further down they mention there was a VT100 Demmo scene

Neat! I personally prefer the very quick vertical tab method: Ctrl+L.

Quick and easy.

cbeams? Isn’t that a Blade Runner reference?

It absolutely is.

ah my old friend `sl’

not to mention the first and only useful application if terminal gif html

CTRL+l gotta go fast!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact