在Linux终端中删除最后执行的命令

6

我想要清除仅最后一条执行的命令。以下是一个示例,以便您更好地理解:

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:~# 

如果当前状态是 shell,我想执行一个命令(例如echo a > /tmp/foo)并保持控制台:
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:~# 

因此,应该是这样的:echo a > /tmp/foo && clear -n 1(我知道clear没有-n 1功能,这只是一个例子)。

谢谢


我相信你正在尝试获取此处解决的问题的答案:https://dev59.com/Smoy5IYBdhLWcg3wkOwK 或者你是在尝试回顾性地删除一个命令? - user4686569
@user4686569:这个问题是关于从shell命令历史记录中删除最后一个命令,但看起来OP只是想要从终端中删除该命令及其输出。 - Michael Jaros
1个回答

2
为了做到这一点,您需要在命令之前保存光标位置,然后在清除屏幕余下部分时恢复位置。下面这个例子可以用来实现这个功能:
$ 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

这可能仅适用于单行提示符。多行提示符可能需要更改参数为 tput cuu。 嗯...将您的提示符作为第一件事运行 tput sc 可能意味着这只需正常工作,而无需玩任何计数/等游戏,但需要进行一些测试。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接