bash script, erase previous line?

You can also use tput cuu1;tput el (or printf '\e[A\e[K') to move the cursor up one line and erase the line:

for i in {1..100};do echo $i;sleep 1;tput cuu1;tput el;done

Small variation on linuts' code sample to move the cursor not to the beginning, but the end of the current line.

{
  for pc in {1..100}; do
    #echo -ne "$pc%\033[0K\r"
    echo -ne "\r\033[0K${pc}%"
    sleep 1
  done
  echo
}

{
  for pc in $(seq 1 100); do
    echo -ne "$pc%\033[0K\r"
    usleep 100000
  done
  echo
}

The "\033[0K" will delete to the end of the line - in case your progress line gets shorter at some point, although this may not be necessary for your purposes.

The "\r" will move the cursor to the beginning of the current line

The -n on echo will prevent the cursor advancing to the next line


printf '\r', usually. There's no reason for cursor addressing in this case.

Tags:

Bash