Skip to content
Advertisement

Delete last executed command in Linux terminal

I want to do a clear but only of the last command I executed. Here is a example so you can understand it better:

root@debian:~# id                               
uid=0(root) gid=0(root) groups=0(root)         
root@debian:~# uname -a 
Linux debian 3.2.0-4-amd64 #1 SMP Debian 3.2.54-2 x86_64 GNU/Linux
root@debian:~# 

If that’s the current state of the shell I want to execute a command (for example echo a > /tmp/foo) and keep the console:

root@debian:~# id                               
uid=0(root) gid=0(root) groups=0(root)         
root@debian:~# uname -a 
Linux debian 3.2.0-4-amd64 #1 SMP Debian 3.2.54-2 x86_64 GNU/Linux
root@debian:~# 

So it should be something like echo a > /tmp/foo && clear -n 1 (I know clear does not have that -n 1 functionality it’s just an example).

Thank you

Advertisement

Answer

To do this you need to save the cursor position before the command and then restore the position after while clearing the rest of the screen.

Something like this should work:

$ hiderun() {
    # Move cursor up one line.
    tput cuu 1
    # Save cursor position.
    tput sc
    # Execute the given command.
    "$@"
    # Restore the cursor position.
    tput rc
    # Clear to the end of the screen.
    tput ed
}

$ id
uid=0(root) gid=0(root) groups=0(root)
$ uname -a
Linux debian 3.2.0-4-amd64 #1 SMP Debian 3.2.54-2 x86_64 GNU/Linux
$ tput sc
$ hiderun do something

This probably only works for a single-line prompt. Multiple line prompts probably need to change the argument to tput cuu.

Hm… having your prompt run tput sc as the first thing might mean this Just Works without needing to play any counting/etc. games but that would need some testing.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement