檢測指令是否已列印到 stderr

檢測指令是否已列印到 stderr

我有這個C語言程序

#include <stdio.h>

int main() {
    char foo[10];
    int i;
    for(i = 0; i < 20 ; i++) {
        foo[i] = 0;
    }

    return 0;
}

如果我運行這個腳本

#!/bin/bash
gcc -O3 -o hello hello.c
if [ $? -eq 0 ]
then
    echo -e "\033[1;32mcompilation sucess!\033[0m"
else
    echo -e "\033[1;31mcompilation error!\033[0m"
fi

它將輸出

hello.c: In function ‘main’:
hello.c:8:10: warning: iteration 10u invokes undefined behavior     [-Waggressive-loop-optimizations]
foo[i] = 0;
    ^
hello.c:6:2: note: containing loop
  for(i = 0; i<20 ;i++)
  ^
compilation sucess!

這是因為 gcc 沒有認為這是一個錯誤,但仍然在stderr.

但我仍然想在 bash 腳本中檢測到這一點。

螢幕截圖

答案1

我認為@DavidPostill的答案是正確的,但如果你想保留警告和錯誤之間的區別,以及檢測註釋,你可以2>err在命令末尾添加gcc

gcc -O3 -o hello hello.c

然後進行測試:

if [ $? -eq 0 -a ! -s err ]

答案2

gcc不認為這是一個錯誤

您可以使用-Werror開關。

-Werror將所有警告變為錯誤。

來源警告選項 - 使用 GNU 編譯器集合 (GCC)

相關內容