Consider this small example:
printf "Loading data..."; \
sleep 5; \
echo -e "\rThis is my cool data point."
This brings, of course, Loading data...
, and after 5 seconds, that will be overwritten by This is my cool data point.
.
But what if the text printed out after the \r
is shorter as the first line?
printf "Loading data..."; \
sleep 5; \
echo -e "\rNo data."
...brings No data.data...
after the waiting time.
Do I have to keep track of the longest possible line and print "\rNo data. "
or is there any "magic character" that fills the line until its end in a normal terminal?
CodePudding user response:
You can delete to end of line with tput el
. So you can do:
eol=$(tput el)
printf "Loading data..."
sleep 5
printf "\rNo data.${eol}\n"
It's not really a "magic character" so much as a "magic sequence", and the actual values that are used may vary with the terminal. tput
will (should) do the right thing and give you a reasonably portable method. Attempting to determine precisely which sequence to use is a futile effort.
CodePudding user response:
Another solution would be:
#!/bin/bash
msg1='Loading data...'
msg2='No data.'
printf '%s' "$msg1"
sleep 5
printf '\r%*s\n' $(( -(${#msg1} > ${#msg2} ? ${#msg1} : ${#msg2}) )) "$msg2"
This appends trailing spaces to the line if the length of msg1
is greater than that of msg2
.