Eric F 🇺🇦
Posted on January 7, 2023
So, clearing the screen in Terminal may be the most trivial thing to do - you type clear
or use the keyboard shortcut Ctrl-L
. And then of course you can/will setup some alias to make it easier.
But, I wanted to do a better setup, to also clear the scrollback. Basically when you type clear
, it'll only push it out of screen, leaving you with a blank screen - but you can still scroll back to the previous output.
Now, there are several ways to do that, and everyone has their own way and habits. This is what I use.
First, there are some distros and other OS's that already do this by default. OS X/macOS will clear the scrollback with its keyboard shortcut, and Debian had that already fixed with their Ctrl-L
. But, not all have that - and just the screen
command definitely doesn't clear it.
Aliases
First you can always have a few handy aliases, like c
& k
.
alias c='clear'
alias k="printf '\\033c'"
The alias k
will clear the scrollback.
Keyboard shortcut
If your keyboard shortcut doesn't clear the scrollback you can map it with a bind
(readline) command. I've seen serveral examples using that. But, one caveat is that whatever command you put in that bind line - it'll end up in the history. So, we have to be creative. :)
Bash have 2 different commands to clear the screen: clear-display (M-C-l)
and clear-screen (C-l)
(see Ref manual). The shortcut Ctrl-L
uses clear-screen
.
I was looking through the list of builtins in my Bash version, and it didn't have clear-display
. Maybe it's gone, because normally - using Ctrl-Alt-L
is the shortcut to lock the (computer) screen, and you'll need to login again. But, that's the command we want.
So, here's the code. You can use this in your .bashrc
or /etc/bashrc
(or where you want to keep your Bash stuff):
# Mimic readline's "clear-display (M-C-l)" behaviour,
# and bind it to C-l (ie. replacing: "clear-screen (C-l)")
function clear-display() {
printf "\\033c" && history -d $(history 1);
}
bind '"\C-l": "\C-e\C-uclear-display\C-m\C-y"'
Ok, so what the code does. It will bind Ctrl-L (\C-l)
to first go to the end of the line (\C-e
) and cut it to the beginning of the line (\C-u
). Then run the function clear-display()
, make a new line (\C-m
), and then paste in what was cut out (\C-y
).
When I was looking at other examples, they used \C-a\C-k
- which is the opposite way. Go to the beginning and cut it from there. I found that way didn't work when pasting it back.
Since everything run by bind will end up in Bash's history… we add history -d $(history 1)
to clear it out.
Well, that's it.
This is maybe a bit overkill, but “old habits” and “muscle memory” are two difficult things to escape. ^_^
// Happy Hacking…
· Eric
Posted on January 7, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.