2016-11-25 83 views
1

我想修改一個最近的Bash別名來轉發錯誤。這裏是別名:修改zsh命令以轉發錯誤

alias 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) 

這個代碼顯示一個C++編譯的結果,然後刪除格式化和顯示和到剪貼板將第一誤差位置(如果有的話)。

不過,我想用這個代碼:

makecclip && bin/someexecutablecreated 

這雖然廢墟&&運營商,因爲它始終運行斌/ someexecutablecreated即使有編譯錯誤存在。當錯誤列表(保存到剪貼板和回顯的東西)不爲空時,如何添加對代碼的修改以設置錯誤標誌?

回答

1

您可以使用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 
+0

我試過,但它似乎並沒有工作。我認爲這實際上是會改變pipestatus的make,但是我也必須重定向錯誤。它是否適用於您的測試? –

+0

是的,它在我的電腦上工作得很好。我編輯了我的問題以添加我使用過的測試。 – Aserre

+0

@AdamHunyadi對不起,我花了一段時間纔將腳本中的測試用例正式化。你可以看到我運行的測試和輸出。 – Aserre