bash - 刷新前 N 行并将光标重置到带有转义序列的当前行的末尾?

标签 bash ansi-escape vt100

情况是这样的,我想做一些终端交互,我想启动子线程刷新前N行,用主线程处理用户输入。

之后程序会打印可变字符串,可能还有一些日志。

子线程是这样的:

    let mut count: i32 = 0;
    loop {
        println!("\x1B[2F\x1B[2KHi user1, count:{}\n", count);
        count += 1;
        let ten_millis = time::Duration::from_millis(1000);
        thread::sleep(ten_millis);
    }

例如:

----------------
Hi user1, count: 0


Input:  1+1
Output: 2
----------------

刷新代码运行良好,但光标将重置为行首,我想始终将其移动到最后一行的末尾。 我怎样才能做到这一点?

如有任何帮助,我们将不胜感激。

最佳答案

当它归结为四处移动光标时,您可能会对简单的ANSI 转义序列感兴趣:

ANSI escape sequences allow you to move the cursor around the screen at will. This is more useful for full screen user interfaces generated by shell scripts, but can also be used in prompts. The movement escape sequences are as follows:

<表类="s-表"> <头> 描述 样本 <正文> 将光标置于L行C列 \033[<L>;<C>H 将光标置于L行C列 \033[<L>;<C>f 光标向上移动N行 \033[<N>A 光标向下移动N行 \033[<N>B 光标向前移动N列 \033[<N>C 光标向后移动N列 \033[<N>D 清屏,移动到(0,0) \033[2J 删除到行尾 \033[K 保存光标位置 \033[s 恢复光标位置 \033[u

source: Bash Prompt HOWTO: Cursor movement

虽然这些 ANSI 转义序列工作得很好,但您可能不时对 tput 的用法感兴趣。因为它为您的脚本提供了更多可读性。讲解 tput这里会有点矫枉过正,但是上面的命令可以这样完成:

<表类="s-表"> <头> 描述 样本 <正文> 将光标置于L行C列 tput cup <L> <C> 光标向上移动N行 tput cuu <N> 光标向下移动N行 tput cud <N> 光标向前移动N列 tput cuf <N> 光标向后移动N列 tput cub <N> 清屏,移动到(0,0) tput clear 删除到行尾 tput el 保存光标位置 tput sc 恢复光标位置 tput rc

还有很多很多其他选项可用。见

  • man tput
  • man 5 terminfo

关于bash - 刷新前 N 行并将光标重置到带有转义序列的当前行的末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53773118/

相关文章:

regex - rsync --exclude-from 'list' 文件不工作

ruby - Ruby 中带有 html 标签的 ANSI 转义代码?

terminal - 通过 ANSI 转义序列或 X11 转义序列禁用回显并设置原始终端模式

c# - 了解 VT100/ANSI 终端

.net - Windows WPF或Silverlight中的VT100终端仿真

linux - Linux 上的 OpenVPN : passing username and password in command line

bash - bash中的关联数组不在循环内存储值

linux - ksh 中的数组长度总是返回 1 以及为什么数组不是行

python - 进度条将不需要的字符打印到控制台

powershell - 在PowerShell控制台中使用ANSI/VT100代码输出彩色文本