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
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.
Simply extend what's already output:
printf "Creating folder..." mkdir foo sleep 2 printf "%32s\n" "Done"
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.