36

I have printed some text using println! and now I need to clear the terminal and write the new text instead of the old. How can I clear all the current text from terminal?

I have tried this code, but it only clears the current line and 1 is still in the output.

fn main() {
    println!("1");
    print!("2");
    print!("\r");
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Haru Atari
  • 1,502
  • 2
  • 17
  • 30
  • 11
    This is no duplicate! This is asking for a way to clear the terminal. The linked "duplicate" is about clearing the current line. The question also states that clearing the current line is not helpful. – itmuckel Oct 13 '17 at 22:41

5 Answers5

58

You can send a control character to clear the terminal screen.

fn main() {
    print!("{}[2J", 27 as char);
}

Or to also position the cursor at row 1, column 1:

print!("{esc}[2J{esc}[1;1H", esc = 27 as char);
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
minghan
  • 1,013
  • 7
  • 12
30
print!("\x1B[2J\x1B[1;1H");

This will clear the screen and put the cursor at first row & first col of the screen.

Markus
  • 2,265
  • 5
  • 28
  • 54
8

Solutions provided by the upvoted answers did not work the way I wanted to. The \x1B[2J\x1B[1;1H sequency only scrolls down the terminal so it actually hides the content and does not clear it. As I wanted to run and infinite loop that re-renders the content shown to the user, this was problem since the scrollbar of my terminal window was shrinking with every "tick".

Inspired from Clear a terminal screen for real I am using

print!("{esc}c", esc = 27 as char);

which works great for me. There might be some drawback on other systems than I use (Ubuntu), I do not know that.

Dan Charousek
  • 132
  • 2
  • 5
2

Try this in the Linux or macOS terminal:

std::process::Command::new("clear").status().unwrap();

In Windows one:

std::process::Command::new("cls").status().unwrap();

This basically sends the "clear" command to terminal.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
moloko824
  • 51
  • 2
0

See the precise answer at cant-run-a-system-command-in-windows given by Vallentin:

use std::{
    error::Error,
    process::Command,
};

fn main() -> Result<(), Box<dyn Error>> {

    clear_terminal_screen();
    println!("Hello World!");

    Ok(())
}

Such that:

pub fn clear_terminal_screen() {
    if cfg!(target_os = "windows") {
        Command::new("cmd")
            .args(["/c", "cls"])
            .spawn()
            .expect("cls command failed to start")
            .wait()
            .expect("failed to wait");
    } else {
        Command::new("clear")
            .spawn()
            .expect("clear command failed to start")
            .wait()
            .expect("failed to wait");
    };
}

See the Rust Playground.

Claudio Fsr
  • 106
  • 6
  • 1
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Feb 23 '23 at 11:29