簡體   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