Search code examples
bashbackspace

Backspacing in Bash


How do you backspace the line you just wrote with bash and put a new one over its spot? I know it's possible, Aptitude (apt-get) use it for some of the updating stuff and it looks great.


Solution

  • Try this:

    $ printf "12345678\rABC\n"
    ABC45678
    

    As you can see, outputting a carriage return moves the cursor to the beginning of the same line.

    You can clear the line like this:

    $ printf "12345678\r$(tput el)ABC\n"
    ABC
    

    Using tput gives you a portable way to send control characters to the terminal. See man 5 terminfo for a list of control codes. Typically, you'll want to save the sequence in a variable so you won't need to call an external utility repeatedly:

    $ clear_eol=$(tput el)
    $ printf "12345678\r${clear_eol}ABC\n"
    ABC