5

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.

Kyle Hotchkiss
  • 10,754
  • 20
  • 56
  • 82

3 Answers3

13

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
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
  • Thanks man. I found that tput is exactly what I am looking for. It's a little awkward to output with it, but that's cool. – Kyle Hotchkiss Jan 11 '11 at 21:49
  • How come I've never seen this command! I remember a big script where I actually used the control characters in the more awkward ways. @KyleHotchkiss don't complain, look at how control characters are output [here](https://bitbucket.org/gokhlayeh/tazpkg/src/f1d05bd96d7f/tazpkg#cl-87) for example (type this in a console: `echo -e '\033[1mbold\033[0m\033[4memphasis\033[0m'`) – Camilo Martin Jul 27 '12 at 19:08
1

It's not really clear to me what you want, but, depending on your terminal settings you can print ^H (control H) to the screen and that will back the cursor up one position.

Also note that some terminals have the ability to move the cursor to the beginning of the line, in which case you'd move to the beginning of the line, print enough spaces to overwrite the entire line (Usually available from $COLUMNS) and then print any message or whatever.

If you clarify exactly what you want and I can answer you I'll update my answer.

JimR
  • 15,513
  • 2
  • 20
  • 26
  • Does that allow you to write over the stuff already there or just push what is already there down? – Kyle Hotchkiss Jan 10 '11 at 06:56
  • @Kyle: It moves the cursor back 1 character. – JimR Jan 10 '11 at 06:58
  • @Kyle: It overwrites. To be more specific, it's not bash you're talking to but the terminal which could either be a gui application or the CRT terminal driver or an actual physical terminal. – slebetman Jan 10 '11 at 07:32
1

Here's an example using the find command & a while-read loop to continually print full file paths to stdout on a single line only:

command find -x / -type f -print0 2>/dev/null | while read -d $'\0' filename; do 
   let i+=1
   filename="${filename//[[:cntrl:]]/}"   # remove control characters such as \n, \r, ...
   if [[ ${#filename} -lt 85 ]]; then
      printf "\r\e[0K\e[1;32m%s\e[0m  %s" "${i}" "${filename}"
   else
      printf "\r\e[0K\e[1;32m%s\e[0m  %s" "${i}" "${filename:0:40}.....${filename: -40}"
   fi
done; echo
carlo
  • 11
  • 1