
我想在命令的輸出中有特定字串時重複該命令,這表示存在錯誤。命令是我想要做的是在中gksu ./installer.run > ./inst.log 2>&1
重複它。如何從 bash 命令列執行此操作?'string'
./inst.log
答案1
在文件中查找字串:
grep -q string file
退出值告訴您 grep 是否發現任何內容。
然後只要指令回傳一個真正的退出值就可以循環:
while command ; do
repeat this
done
雖然您想至少運行該命令一次,所以也許
while true ; do
some command
if ! grep -q string file ; then
break # jump out of the loop if it's _not_ there
fi
done
否則,您需要在循環之前和循環內部重複該命令。
答案2
請注意,在 中while while-cmd-list; do do-cmd-list; done
,while-cmd-list
是也命令列表。它不一定是單一命令。
所以你可以這樣做:
while
gksu ./installer.run > ./inst.log 2>&1
grep -q string inst.log
do
echo >&2 "Trying again, output contained string"
done
雖然在這裡,你也可以這樣做:
while
gksu ./installer.run 2>&1 |
tee ./inst.log |
grep string > /dev/null
do
echo >&2 "Trying again, output contained string"
done
(請注意,我們沒有使用-q
,因為這意味著可能grep
會提前退出,導致安裝程式收到 SIGPIPE)。