您可以使用PIPESTATUS
內部變量(該變量在非bash shell中具有其他名稱)來解決您的問題。這允許具有管道傳遞的命令的退出狀態的歷史記錄。
你一種高精度的,你沒有使用bash
的意見,但使用zsh
代替。因此,我的解決方案的一些語法必須改變,因爲它們以不同方式處理PIPESTATUS
變量。
在bash中,您使用${PIPESTATUS[0]}
,而您將在zsh中使用${pipestatus[1]}
。
第一種方法,使用現有的別名,可能是如下:
makecclip && [ "${pipestatus[1]}" -eq "0" ] && echo "ok"
這將運行僅當"${pipestatus[1]}"
等於0(make的過程中沒有錯誤)
的echo
命令更方便的解決方案是使用函數而不是別名makecclip
。在你~/.bashrc
文件,你可以寫:
makecclip() {
make |& tee >(sed "s,\x1B\[[0-9;]*[a-zA-Z],,g" | egrep ":[0-9]+:[0-9]+: error" | cut -d : -f1,2,3 | head -n 1 | xargs -0 echo -n | xclip -selection clipboard && xclip -selection clipboard -o)
return "${pipestatus[1]}"
}
現在,makecclip && echo "ok"
會達到預期效果。
測試用例:
#!/bin/zsh
#do not run this test if there is an existing makefile in your current directory
rm -f makefile
makecclip() {
make |& tee >(sed "s,\x1B\[[0-9;]*[a-zA-Z],,g" | egrep ":[0-9]+:[0-9]+: error" | cut -d : -f1,2,3 | head -n 1 | xargs -0 echo -n | xclip -selection clipboard && xclip -selection clipboard -o)
# this part is only present to check the pipestatus values during the tests.
# In the real function, I wrote 'return ${pipestatus[1]}' instead.
a=(${pipestatus[@]})
echo ${a[@]}
return ${a[1]}
}
echo "# no makefile"
makecclip && echo "ok"
echo -e "\n# empty makefile"
touch makefile
makecclip && echo "ok"
echo -e "\n# dummy makefile entry"
echo -e 'a:\n\[email protected] "inside makefile"' > makefile
makecclip && echo "ok"
echo -e "\n# program with error makefile"
echo -e "int main(){error; return 0;}" > target.cc
echo -e 'a:\n\tgcc target.cc' > makefile
makecclip && echo "ok"
輸出:
$ ./test.sh
# no makefile
make: *** No targets specified and no makefile found. Stop.
2 0
# empty makefile
make: *** No targets. Stop.
2 0
# dummy makefile entry
inside makefile
0 0
ok
# program with error
gcc target.cc
target.cc: In function ‘int main()’:
target.cc:1:12: error: ‘error’ was not declared in this scope
int main(){error; return 0;}
^
makefile:2: recipe for target 'a' failed
make: *** [a] Error 1
target.cc:1:12
2 0
我試過,但它似乎並沒有工作。我認爲這實際上是會改變pipestatus的make,但是我也必須重定向錯誤。它是否適用於您的測試? –
是的,它在我的電腦上工作得很好。我編輯了我的問題以添加我使用過的測試。 – Aserre
@AdamHunyadi對不起,我花了一段時間纔將腳本中的測試用例正式化。你可以看到我運行的測試和輸出。 – Aserre