如何在bash中获取光标位置?

前端之家收集整理的这篇文章主要介绍了如何在bash中获取光标位置?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在一个bash脚本中,我想将光标列放在一个变量中。看起来像使用ANSI转义码{ESC} [6n是获取它的唯一方法,例如以下方式:
  1. # Query the cursor position
  2. echo -en '\033[6n'
  3.  
  4. # Read it to a variable
  5. read -d R CURCOL
  6.  
  7. # Extract the column from the variable
  8. CURCOL="${CURCOL##*;}"
  9.  
  10. # We have the column in the variable
  11. echo $CURCOL

不幸的是,这将打印字符到标准输出,我想静静地做。此外,这不是很便携…

有没有一个纯粹的bash方式来实现这一点?

你必须诉诸肮脏的技巧:
  1. #!/bin/bash
  2. # based on a script from http://invisible-island.net/xterm/xterm.faq.html
  3. exec < /dev/tty
  4. oldstty=$(stty -g)
  5. stty raw -echo min 0
  6. # on my system,the following line can be replaced by the line below it
  7. echo -en "\033[6n" > /dev/tty
  8. # tput u7 > /dev/tty # when TERM=xterm (and relatives)
  9. IFS=';' read -r -d R -a pos
  10. stty $oldstty
  11. # change from one-based to zero based so they work with: tput cup $row $col
  12. row=$((${pos[0]:2} - 1)) # strip off the esc-[
  13. col=$((${pos[1]} - 1))

猜你在找的Bash相关文章