1

目标

直到脚本中的某个子任务完成其工作:

  • 停止回声;
  • 禁用光标;
  • 消耗所有用户输入;
  • 不要阻塞中断(Ctrl+C 等)。

做了什么

现在,使用这个答案,我为此创建了几个函数,它们是:

function hide_input()
{
  if [ -t 0 ]; then
    stty -echo -icanon time 0 min 0
  fi
}

function reset_input()
{
  if [ -t 0 ]; then
    stty sane
  fi
}

function stop_interactive()
{
  trap reset_input EXIT
  trap hide_input CONT
  hide_input
  tput civis
}

function start_interactive()
{
  tput cnorm
  reset_input
}

function consume_input()
{
  local line
  while read line; do line=''; done
}

以下是它们的使用方式:

echo "Warn the user: the job will be started."
read -p "Continue? [yes/no] > "
if [ "$REPLY" == "yes" ]; then
  stop_interactive  # <== from here all input should be rejected
  echo "Notify the user: job starting..."

  # << ------ here goes some long job with output to terminal ------>

  echo "Notify the user: job done!"
  consume_input # <== here I trying to get all user input and put nowhere
  start_interactive # <== from here restore normal operation
else
  echo "Aborted!"
  exit 0
fi

问题

问题是:当前的“解决方案”不起作用。当我在长时间运行的作业中按下键时,它们会出现在屏幕上,并且按“Enter”会破坏所有输出并伴随光标移动。此外,在“start_interactive”函数调用之后,所有输入都出现在终端屏幕上。

这项任务的正确解决方案是什么?

解决方案

最终的工作解决方案是:

function hide_input()
{
  if [ -t 0 ]; then
    stty -echo -icanon time 0 min 0
  fi
}

function reset_input()
{
  if [ -t 0 ]; then
    stty sane
  fi
}

function consume_input()
{
  local line
  while read line; do line=''; done
}

function stop_interactive()
{
  trap reset_input EXIT
  trap hide_input CONT
  hide_input
  tput civis
}

function start_interactive()
{
  consume_input
  trap - EXIT
  trap - CONT
  tput cnorm
  reset_input
}

echo "Warn the user: the job will be started."
read -p "Continue? [yes/no] > "
if [ "$REPLY" == "yes" ]; then
  stop_interactive
  echo "Notify the user: job starting..."
  do_the_job &
  pid=$!
  while ps $pid > /dev/null ; do
    consume_input
  done
  echo "Notify the user: job done!"
  start_interactive
else
  echo "Aborted!"
  exit 0
fi
4

1 回答 1

2

根据您的问题,如果我查看您的代码,会有很多“为什么”的问题。如果您不想更改 ^C 等的行为,请不要使用陷阱。您的所有函数都测试文件描述符 0 是否是终端。你打算在管道中使用脚本吗?此外,您对用户输入的使用将一直持续到文件结束,因此脚本可能永远不会结束。

根据你的问题,我会写这样的东西:

echo "Warn the user: the job will be started."
read -p "Continue? [yes/no] > "
if [ "$REPLY" == "yes" ]; then
    stty -echo
    echo "Notify the user: job starting..."
    program_to_execute &
    pid=$!
    while ps $pid > /dev/null ; do
        read -t 1 line
    done
    echo "Notify the user: job done!"
else
    echo "Aborted!"
fi
stty sane
于 2017-12-23T16:04:19.263 回答