Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 383
Ryan Fold Avatar asked Mar 18 '15 17:03

Ryan Fold


1 Answers

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.

like image 170
Etan Reisner Avatar answered Sep 30 '22 16:09

Etan Reisner