繁体   English   中英

在Linux中使用bash脚本通过轮询按键来启动和停止尾部

[英]Using a bash script in linux to start and stop tail by polling for keypress

这是我想要做的,我有一个带有温度信息的arduino,它通过串行方式进入linux机顶盒。 我已成功读取序列并将其记录到cat中,然后在文件后添加tail -f。 作品出色。 我想在一些控件中做广告,以便能够尾部文件,停止尾部但继续记录或一起关闭程序。 所以这就是我以为我在这里成功完成的工作,但是我从linux中得到了最奇怪的错误。 我讨厌手动杀死猫,我想要一个很好的简单小界面。 我尝试了许多不同的方法来获得这些结果,并且对新方法持开放态度。

最初,当我开始我的程序时,发生以下错误

./arduinodue.sh: 20: ./arduinodue.sh: [[: not found
./arduinodue.sh: 25: ./arduinodue.sh: [[: not found

如果我按任何键,这将开始向下滚动屏幕

Press S to start and stop tail

Press X to close and stop recording

最终在点击了s或x次之后我得到了

Segmentation fault (core dumped)

我的代码如下:

#!/bin/sh

#below opens serial connection

stty -F /dev/ttyACM0 cs8 19200 ignbrk -brkint -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts

cat /dev/ttyACM0 > $HOME/Due.log &     #starts cat recording serial data to Due.log as a background task
PID1=$!     #records PID of cat

nottailing2() {     #prints a message with instructions
echo "\n"
echo "Press S to start and stop tail\n"
echo "Press X to close and stop recording\n"
nottailing
}

nottailing() {     #starts a while loop waiting for a keypress I attempted running without while loop and instead used function calls to redirect the run sequence with simular results
if [ -t 0 ]; then stty -echo -icanon time 0 min 0; fi     #makes a keypress interrupt I believe but I've also attempted to run without that
while [ "x$keypress" = "x" ]; do
keypress=''
read keypress
if [[ "$keypress" == [X,x]* ]]; then     #press x to kill the script cleanly
if [ -t 0 ]; then stty sane; fi
kill $PID1
exit 1
fi
if [[ "$keypress" == [S,s]* ]]; then     #press s to start tail
if [ -t 0 ]; then stty sane; fi     #close interrupt?
break
fi
done
if [ -t 0 ]; then stty sane; fi
tailing
}

tailing() {     #same as function nottailing except it stops the tailing instead of starting it
if [ -t 0 ]; then stty -echo -icanon time 0 min 0; fi
while [ "x$keypress" = "x" ]; do
keypress=''
read keypress
if [[ "$keypress" == [X,x]* ]]; then
if [ -t 0 ]; then stty sane; fi
kill $PID1
exit 1
fi
if [[ "$keypress" == [S,s]* ]]; then
if [ -t 0 ]; then stty sane; fi
break
fi
done
if [ -t 0 ]; then stty sane; fi
nottailing2
}

nottailing2     #start the looping process

这个:

./arduinodue.sh: 20: ./arduinodue.sh: [[: not found

这是一个好信号,表明您使用的是为Bash(或其他Shell)编写的代码,但在POSIX极简外壳中运行它。 您的脚本在顶部显示/bin/sh ,因此您不能使用[[确实。 如果您的系统具有Bash,请更改顶部的shebang行。 如果没有,您将需要找到另一种方法来进行那些检查,而无需使用[[语法。 也许这:

if [ "$keypress" = S -o "$keypress" = s ]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM