jot*_*iez 5 bash background input
我想处理用户输入,但在后台,就像在新线程中一样.
例如,显示进度条,当用户点击时R,进度条重置,或者如果用户点击Q,则脚本退出.
我不希望脚本等待用户输入.只需渲染所有内容,如果用户点击任何键,则执行某些操作.
它在bash中是可行的吗?
提前致谢.
编辑:我需要脚本总是读取用户输入,但不要中断主循环的执行.复杂我让自己用英语理解
_handle_keys()
{
    read -sn1 a
    test "$a" == `echo -en "\e"` || continue
    read -sn1 a
    test "$a" == "[" || break
    read -sn1 a
    case "$a" in
        C) # Derecha
            if [ $PALETTE_X -lt $(($COLUMNS-$PALETTE_SIZE)) ] ; then
                PALETTE_X=$(($PALETTE_X+1))
            fi
        ;; 
        D) # Izquierda
            if [ $PALETTE_X -gt 0 ] ; then
                PALETTE_X=$(($PALETTE_X-1))
            fi
        ;;
    esac
}
render()
{
    clear
    printf "\033[2;0f BALL (X:${BALL_X} | Y:${BALL_Y})"
    _palette_render # Actualiza la paleta
    _ball_render
}
while true
do
    LINES=`tput lines`
    COLUMNS=`tput cols`
    render
    _handle_keys
done
在我的脚本中,只有在按下某个键时球才会移动(render> _ball_render),因为_handle_keys等待用户输入.
我做了一个丑陋的解决方案,read -t0.1但不喜欢这个
PD:抱歉,我的最后一条评论,编辑过程中的时间编辑结束
这是一种似乎有用的技术.我基于Sam Hocevar对Bash的回答:如何用任何按键结束无限循环?.
#!/bin/bash
if [ ! -t 0 ]; then
  echo "This script must be run from a terminal"
  exit 1
fi
stty -echo -icanon time 0 min 0
count=0
keypress=''
while true; do
  let count+=1
  echo -ne $count'\r'
  # This stuff goes in _handle_keys
  read keypress
  case $keypress in
  # This case is for no keypress
  "")
    ;;
  $'\e[C')
    echo "derecha"
    ;;
  $'\e[D')
    echo "izquierda"
    ;;
  # If you want to do something for unknown keys, otherwise leave this out
  *)
    echo "unknown input $keypress"
    ;;
  esac
  # End _handle_keys
done
stty sane
如果stty sane错过了(例如因为脚本被Ctrl- 而被杀死C),终端将处于奇怪的状态.您可能需要查看trap声明以解决此问题.