Saturday, 14 March 2026

Moving the cursor using printf

Controlling the Cursor in Bash Using ANSI Escape Codes 🖥️

When working with terminal applications or interactive shell scripts, it is sometimes useful to control where text appears on the screen.

Using ANSI escape sequences, Bash scripts can:

  • Move the cursor

  • Save and restore cursor position

  • Build interactive terminal tools

  • Create dynamic dashboards

  • This article explains the most useful cursor movement commands in Bash and demonstrates a simple script that moves the cursor, prints text, and restores the cursor position.

1️⃣ Useful Cursor Commands for Bash

ANSI escape codes allow you to control the cursor position inside the terminal.

CodeMeaning
\e[HMove cursor to top-left corner
\e[10;10HMove cursor to row 10, column 10
\e[AMove cursor up
\e[BMove cursor down
\e[CMove cursor right
\e[DMove cursor left
\e[7Save cursor position
\e[8Restore cursor position

These codes are interpreted by the terminal when printed using commands such as printf.


2️⃣ Example Bash Script: Moving the Cursor

Below is a simple script demonstrating how to:

  • Save the cursor position

  • Move the cursor to another location

  • Print text

  • Restore the cursor

Your original script:

[root@oel01db Shell-Scripting]# cat 01-Move-Cursor.sh

#!/usr/bin/env bash

# save the cursor position
printf '\e7'

# jump somewhere
printf '\e[20;20H'

# print "hello world"
printf 'Hello World'

# restore the cursor
printf '\e8'

[root@oel01db ShellHello World#




























3️⃣ How the Script Works

Let's break down each step.


Step 1 — Save the Cursor Position

printf '\e7'

This command saves the current cursor position.

The terminal remembers where the cursor is located so it can be restored later.

This is useful when you temporarily move the cursor somewhere else but want to return to the original position afterward.


Step 2 — Move the Cursor

printf '\e[20;20H'

This ANSI escape sequence moves the cursor to:

Row 20
Column 20

Structure of the command:

\e[<row>;<column>H

So in this example:

\e[20;20H

means:

👉 Move the cursor to line 20, column 20.


Step 3 — Print Text

printf 'Hello World'

Since the cursor was moved to position 20,20, the text appears exactly at that location on the terminal screen.


Step 4 — Restore the Cursor

printf '\e8'

This restores the cursor to the previous saved position.

As a result, the script briefly moves the cursor to another location, prints the message, and then returns to the original position.



4️⃣ Alternative Save and Restore Codes

Some terminals support a slightly different syntax:

CommandMeaning
\e[sSave cursor position
\e[uRestore cursor position

Example:

printf '\e[s'
printf '\e[10;10H'
printf 'Hello'
printf '\e[u'

These are considered more portable across different terminal emulators.


5️⃣ Clearing the Screen

Many terminal programs also combine cursor movement with screen control.

For example:

\e[2J

This clears the entire terminal screen.

Example:

printf '\e[2J'
printf '\e[H'

Meaning:

  1. Clear screen

  2. Move cursor to the top

This is commonly used in terminal dashboards.


6️⃣ Practical Uses of Cursor Movement

Cursor control is extremely useful when building interactive terminal programs.

Examples include:

Terminal dashboards

Updating values without scrolling.

Example:

CPU Usage: 30%
Memory Usage: 50%
Disk Usage: 70%

The script updates numbers in place.


Progress bars

Example:

Downloading: [##########------] 50%

The cursor moves back and updates the same line.


Interactive CLI tools

Tools like:

  • htop

  • top

  • watch

  • ncurses applications

all rely heavily on cursor positioning.


7️⃣ Best Practice: Use printf Instead of echo

When printing ANSI escape sequences, it is better to use printf instead of echo.

Reason:

echo behavior can vary between shells, while printf handles escape sequences more reliably.

Example:

printf '\e[10;10HHello'

8️⃣ Quick Demo Script

Here is a simple script that demonstrates cursor movement:

#!/usr/bin/env bash

printf '\e[2J' # clear screen
printf '\e[5;10HHello'
printf '\e[7;10HWorld'
printf '\e[10;10HDone'

Output will appear at different positions on the terminal screen.


4️⃣ Moving the Cursor Using tput

Instead of using raw ANSI escape sequences, you can use the tput command.

tput interacts with the terminfo database, which describes the capabilities of the current terminal.

This makes scripts more portable across different terminal types.

Your script using tput:

[root@oel01db Shell-Scripting]# cat o1-Move-Cursor-Using-tput.sh
#!/usr/bin/env bash

# Save the cursor position
tput sc

# Move cursor to Row 20, Column 20
# Note: tput uses 0-based indexing (0 0 is top-left)
tput cup 20 20

# Print the text
printf 'Hello World'

# Restore the cursor position
tput rc
[root@oel01db Shell-Scripting]#

5️⃣ How the tput Script Works

Save Cursor Position

tput sc

sc means Save Cursor.


Move Cursor

tput cup 20 20

cup means Cursor Position.

Syntax:

tput cup ROW COLUMN

Important difference:

tput uses 0-based indexing.

So:

0 0

is the top-left corner of the terminal.


Print Text

printf 'Hello World'

The text appears at the cursor location.


Restore Cursor

tput rc

rc means Restore Cursor.

This moves the cursor back to the previously saved position.


6️⃣ Comparison: ANSI Escape Codes vs tput

FeatureANSI Escape Codestput
SpeedSlightly fasterSlightly slower
PortabilityDepends on terminal supportHighly portable
ReadabilityHarder to readEasier to understand
DependenciesNo external commandRequires tput
CompatibilityWorks on most modern terminalsWorks across many terminal types

Example comparison:

ANSI version

printf '\e[20;20H'

tput version

tput cup 20 20

Both perform the same task, but tput is usually more portable.

6️⃣ An example for progress bar is given below.

 #!/usr/bin/env bash

# Define colors and styles

BLUE=$(tput setaf 4)

GREEN=$(tput setaf 2)

RESET=$(tput sgr0)

BOLD=$(tput bold)

# Hide the cursor so it doesn't flicker

tput civis

# Function to draw the bar

draw_bar() {

    local percentage=$1

    local width=20

    # Calculate how many # to draw (percentage * width / 100)

    local filled=$(( percentage * width / 100 ))

    local empty=$(( width - filled ))

    # Prepare the bar string

    # printf -v allows saving the output to a variable

    printf -v bar_filled "%${filled}s" ""

    printf -v bar_empty "%${empty}s" ""

    # \r moves cursor to the start of the line

    # Use ${bar_filled// /#} to replace spaces with #

    # Use ${bar_empty// /-} to replace spaces with -

    printf "\r${BOLD}Downloading: ${RESET}[${BLUE}${bar_filled// /#}${RESET}${bar_empty// /-}] ${GREEN}%3d%%${RESET}" "$percentage"

}

# Simulation Loop

for i in {0..100..5}; do

    draw_bar "$i"

    sleep 0.2

done

# Show the cursor again and move to a new line

tput cnorm

echo -e "\nDownload Complete!"

Color coding in bash

Bash Script to Display All 256 ANSI Terminal Colors 🎨

Many modern terminals support the ANSI 256-color palette, allowing scripts and command-line tools to display colored text.

Using colors in terminal output makes scripts easier to read and is commonly used for:

  • Shell scripts

  • CLI tools

  • Log highlighting

  • Prompt customization

  • Monitoring scripts

The following Bash script prints all 256 terminal colors (0–255) so you can visually inspect how each color appears in your terminal.


1️⃣ The Bash Script

#!/usr/bin/env bash

for i in {0..255}; do
printf '\e[38;5;%dmColor %d\e[0m\n' "$i" "$i"
done

This simple loop prints the text “Color N” using each of the 256 ANSI colors.

























2️⃣ Understanding the Loop {0..255}

for i in {0..255}

This syntax is called Bash brace expansion.

It generates the numbers:

0 1 2 3 ... 255

So the loop runs 256 times, storing each value in the variable i.

Example iterations:

i=0
i=1
i=2
...
i=255

Each value corresponds to a specific ANSI color index.


3️⃣ The printf Command

printf '\e[38;5;%dmColor %d\e[0m\n' "$i" "$i"

printf prints formatted text to the terminal.

It works similarly to the C programming language printf() function.

In this script, it performs two tasks:

  1. Applies a color escape sequence

  2. Prints the color number


4️⃣ Understanding the ANSI Color Escape Code

\e[38;5;%dm

This is an ANSI escape sequence that tells the terminal to change the text color.

PartMeaning
\eEscape character
[Start of ANSI control sequence
38Set foreground text color
5Use 256-color mode
%dColor number (0–255)
mApply formatting

Example

When i=34 the sequence becomes:

\e[38;5;34m

This tells the terminal:

👉 Set the foreground text color to color 34


5️⃣ The Printed Text

Color %d

%d is replaced with the current value of i.

Example output:

Color 34

But the text “Color 34” appears in color 34.


6️⃣ Resetting Terminal Formatting

\e[0m

This sequence resets all terminal formatting.

Without resetting:

  • The terminal would keep using the same color

  • All text printed afterwards would remain colored

Resetting ensures the terminal returns to default colors.


7️⃣ Example Output

When the script runs, you will see:

Color 0
Color 1
Color 2
...
Color 255

Each line appears in its corresponding color, creating a visual color reference chart directly inside your terminal.


8️⃣ Understanding the ANSI 256-Color Palette

The 256-color palette is organized into three sections:

RangeDescription
0–15Standard system colors
16–2316×6×6 RGB color cube
232–255Grayscale ramp

This means the terminal supports:

  • Basic colors

  • Extended RGB-style colors

  • Grayscale shades


9️⃣ Using True RGB Colors (24-bit Color)

Modern terminals also support True Color (24-bit color).

Instead of:

38;5;<color>

You can use:

38;2;<R>;<G>;<B>m

Structure:

\e[38;2;<R>;<G>;<B>m

Where:

ValueMeaning
RRed intensity (0–255)
GGreen intensity (0–255)
BBlue intensity (0–255)

🔴 Example: Pure Red Text

printf "\e[38;2;255;0;0mHello\e[0m\n"

Meaning:

ValueMeaning
255Red
0Green
0Blue

Output:

Hello

Displayed in bright red.


🔟 Additional ANSI Styling Options

ANSI codes can also control text styles.

CodeEffect
1Bold
4Underline
7Reverse
0Reset

Example

printf "\e[1;38;5;196mBold Red Text\e[0m\n"

This prints bold bright red text.


1️⃣1️⃣ Background Colors

To change the background color, use 48 instead of 38.

Example:

printf "\e[48;5;34mBackground Color\e[0m\n"

This prints text with background color 34.


1️⃣2️⃣ Checking Terminal Color Support

You can check whether your terminal supports 256 colors.

Method 1

echo $TERM

Method 2

tput colors

Example output:

256

This means your terminal supports the 256-color palette.


1️⃣3️⃣ Using tput for Portable Color Scripts

Instead of raw escape sequences, you can also use the tput command, which interacts with the terminfo database.

This approach is more portable across terminals.

Example script:

[root@oel01db Shell-Scripting]# cat 02-color-text-using-tput.sh

#!/usr/bin/env bash

# Define colors

RED=$(tput setaf 1)

GREEN=$(tput setaf 2)

YELLOW=$(tput setaf 3)

RESET=$(tput sgr0)

# Use them in your script

echo "${RED}Error:${RESET} Something went wrong."

echo "${GREEN}Success:${RESET} File moved."

echo "${YELLOW}Warning:${RESET} Disk space is low."

[root@oel01db Shell-Scripting]#












1️⃣4️⃣ Why tput Is Often Preferred

tput is useful because:

  • It abstracts terminal capabilities

  • It works across different terminal types

  • It relies on the terminfo database

Common commands:

CommandMeaning
tput setaf NSet foreground color
tput setab NSet background color
tput boldBold text
tput sgr0Reset formatting

1️⃣5️⃣ Practical Use Cases

Colorized terminal output is extremely useful for:

1. Log highlighting

ERROR (red)
WARNING (yellow)
SUCCESS (green)

2. Deployment scripts

Clear feedback during automation.

3. Monitoring scripts

Color helps quickly identify issues.

4. Custom Bash prompts

Many developers use colors in the PS1 prompt.


Conclusion

The ANSI color system allows Bash scripts to produce rich, readable terminal output.

Using either ANSI escape sequences or the tput command, you can easily:

  • Colorize logs

  • Improve CLI tools

  • Create visually helpful scripts

  • Customize your shell environment

The 256-color reference script is a simple yet powerful tool for understanding how colors appear in your terminal.

JFrog Artifactory - How to install

JFrog Artifactory OSS Installation Guide CentOS 9 + PostgreSQL 17 This guide provides a structured workflow to install JFrog Artifactory OSS...