简体   繁体   中英

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 eg 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 eg

    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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM