开发者

Backspacing in Bash

开发者 https://www.devze.com 2023-02-03 03:59 出处:网络
How do you backspace the line you just wrote with bash and put a new one over its sp开发者_如何学Goot? I know it\'s possible, Aptitude (apt-get) use it for some of the updating stuff and it looks grea

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


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


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消