How to Change Cursor Position in Terminal
Overview
To change the cursor position in the terminal, output special characters. Controlling the cursor position this way to repeatedly update output is useful for showing progress or lists without wasting lines.
\r
: carriage return, moves the cursor to the beginning of the current line.\x1b[1A
: move to the previous line, an ANSI escape code.\x1b[F
: move to the beginning of the previous line, an ANSI escape code.
Here, \x1b
is the escape character that starts an ANSI escape sequence.
Example
The animation above shows the execution of Julia code that displays a mock loading screen. The underlying principle is simply printing strings, so it can be implemented similarly in other languages.
println("loading...")
for i in 1:100
print("\r", i, "%")
sleep(0.01)
end
print("\x1b[F", "done!", " " ^ 10)