2012-07-04 50 views
0

請考慮以下幾點:命令的grep輸出有時會起作用..有時候不行?

$ cd ~/.emacs.d/lisp/tabbar 
$ git pull 
Already up-to-date. 

$ git pull | grep -q "Already" ; echo $? 
0 

還是?現在:

$ cd ~/src/emacs-tmp/trunk 
$ bzr up       
Tree is up to date at revision 108837 of branch /home/px/src/emacs-tmp/trunk 

$ bzr up | grep -q "Tree" ; echo $?  
Tree is up to date at revision 108837 of branch /home/px/src/emacs-tmp/trunk 
1 

問題:

  • 爲什麼grep的返回碼 「0」(發現)在第一種情況下和 「1」(未找到)在第二個?
  • 爲什麼輸入的第一個(git pull)命令是 ?

回答

1

看起來BZR被輸出到標準錯誤設備(/dev/stderr),而grep僅檢查標準輸入。您可以確認或試圖通過重定向stderrstdin否認這個猜測:

bzr up 2>&1 | grep -q "Tree" ; echo $? 
1

我認爲你的「可見」命令輸出到stderr而不是stdout。的grep只查找標準輸出,除非使用2> & 1.

因此重定向嘗試

bzr up 2>&1 | grep -q "Tree" ; echo $? 
1
  • 爲什麼grep的返回碼「0」(發現)在第一種情況下和(未找到)中的「1」第二?

可能是因爲在第一種情況下輸出在標準輸出上,而在第二種情況下它在標準錯誤上。您可以在命令中添加一個「2> & 1」,以便將所有內容全部轉換爲stadout。

  • 爲什麼第一個(git pull)命令的輸出在進行grepping時會隱藏?

因爲你說「-q」,它告訴grep閉嘴:-)

相關問題