好的,我想我有解决方案。我接受了 nhed 的提议并做了一些工作:)
主代码打印一些状态并等待输入:
while :
do
# print the progress on the screen
echo -n "Enter command: "
tput sc # save the cursor position
echo -n "$tmpBuffer" # this is buffer which holds typed text (no 'ENTER' key yet)
waitForUserInput
read arguments <<< $(echo $mainBuffer) # this buffer is set when user presses 'ENTER'
mainBuffer="" # don't forget to clear it after reading
# now do the action requested in $arguments
done
函数 waitForUserInput 等待 10 秒等待按键。如果没有输入 - 退出,但已经输入的键被保存在缓冲区中。如果按键被按下,它会被解析(添加到缓冲区,或者在退格的情况下从缓冲区中删除)。On Enter 缓冲区被保存到另一个缓冲区,从中读取它以进行进一步处理:
function waitForUserInput {
saveIFS=$IFS # save current IFS
IFS="" # change IFS to empty string, so 'ENTER' key can be read
while :
do
read -t10 -n1 char
if (( $? == 0 ))
then
# user pressed something, so parse it
case $char in
$'\b')
# remove last char from string with sed or perl
# move cursor to saved position with 'tput rc'
echo -n "$tmpBuffer"
;;
"")
# empty string is 'ENTER'
# so copy tmpBuffer to mainBuffer
# clear tmpBuffer and return to main loop
IFS=$saveIFS
return 0
;;
*)
# any other char - add it to buffer
tmpBuffer=$tmpBuffer$char
;;
esac
else
# timeout occured, so return to main function
IFS=$saveIFS
return 1
fi
done
}
感谢大家的帮助!