运营商" 2>>"在shell脚本中做什么?

时间:2014-02-21 06:02:35

标签: shell sh

我从c.learncodethehardway.org/book/ex28.html

中读取了以下代码
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

1 个答案:

答案 0 :(得分:3)

>>运算符通常启用输出重定向到文件并追加而不是替换它(>运算符替换)。

任何重定向运算符前面的数字都定义了要重定向的流号,在本例中为stderr

因此some-command 2>> filestderr - some-command的输出附加到文件file

顺便说一句:2>>&1stderr的内容重定向到与stdout相同的流,这通常用于在单个管道命令中查看两个流:

some-command 2>&1 | less

这会将stderrstdout同时发送到less,因为2>&1混合了stderrstdout流然后用管道输送到less

示例中的if2>>无关,它只会评估valgrind的返回值。

相关问题