bash printf - how to align text to right in the same line without deleting previous output

I'm trying to have in script Done or Fail statuses aligned to the right of previous text. But not e.g. 50 chars from last character, but 50 chars from left side of terminal. I'm not printing it using single, but multiple printf's. In code I have e.g.

    printf "Creating folder..."
    sleep 2
    mkdir foo
    printf "\r%50.10s\n" "Done"

Unfortunately it keeps me outputting

                                                  Done

instead of

    Creating folder...                            Done

Is there a possibility to align text to right in the same line without deleting previous output?

Debian 8, bash 4.3.30

Answers


There are a couple of options, at least.

  1. Simply extend what's already output:

    printf "Creating folder..."
    mkdir foo
    sleep 2
    printf "%32s\n" "Done"
    
  2. Rewrite what was already output:

    printf "Creating folder..."
    mkdir foo
    sleep 2
    printf "\r%-50s %s\n" "Creating folder..." "Done"
    

I moved the sleep after the mkdir to give you some chance to read error messages from mkdir before the printf kicks in again.

You might want to think about showing the folder name in the messages too.


You can use an ANSI escape code to explicitly position the cursor in column 50:

printf "Creating folder..."
sleep 2
mkdir foo
printf "\033[50G%s\n" "Done"
        ^^^^^^^^

This does not require calculating a width based on how much was already printed or reprinting the first part of the line. It does assume a terminal that processes ANSI escape codes, though.


Need Your Help

Create a function which will return 4 output columns

sql-server tsql

Create table holiday master which will have column name as holiday date,day (Sunday,monday or any public holiday holiday).

C++ library for Coordinate Transformation Matrices (CTM)?

c++ coordinates postscript

I'm looking for a C++ library which allows for easy integration of Coordinate Transformation Matrices (CTM) in my application. You might know CTMs from PDF or PostScript.