2014-02-21 41 views
2

我讀了c.learncodethehardway.org/book/ex28.html運算符「2 >>」在shell腳本中做了什麼?

echo "Running unit tests:" 

for i in tests/*_tests 
do 
    if test -f $i 
    then 
     if $VALGRIND ./$i 2>> tests/tests.log 
     then 
      echo $i PASS 
     else 
      echo "ERROR in test $i: here's tests/tests.log" 
      echo "------" 
      tail tests/tests.log 
      exit 1 
     fi 
    fi 
done 

echo "" 

下面的代碼是什麼操作 「2 >>」 在shell腳本呢?

而且,之前我問這個問題,我已經測試了它的命令行,這就是我的了:

~/Projects/test> if 0 2>> hello.txt; then echo "0"; else echo "?"; fi 
? 
~/Projects/test> if 1 2>> hello.txt; then echo "0"; else echo "?"; fi 
? 
~/Projects/test> if 108230284 2>> hello.txt; then echo "0"; else echo "?"; fi 
? 
~/Projects/test> if 0 2>> hello.txt; then echo "0"; else echo "?"; fi 
? 

~/Projects/test> cat hello.txt 
-bash: 0: command not found 
-bash: 1: command not found 
-bash: 108230284: command not found 
-bash: 0: command not found 
+0

請參閱:http://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/comparison-ops.html \ –

回答

3

>>運算符通常能夠輸出重定向到一個文件,附加而不是替換它(>運算符替換)。

任何重定向操作員前面的數字定義要重定向的流號碼,在本例中爲stderr

所以some-command 2>> file追加的some-commandstderr -outputs到文件file

順便說一句:2>>&1重定向的stderr到相同的流作爲stdout內容,這通常用於查看在一個單一的管道命令兩個流:

some-command 2>&1 | less 

這將管既stderrstdoutless,因爲2>&1stderr中混合到stdout流,然後通過管道流向less

您示例中的if2>>無關,它將簡單地評估返回值valgrind