3

I have a tricky requirement:

I need to use bash to compile 100 programs, say 1.c, 2.c, 3.c ... 100.c, I want to keep those c programs which was compiled successfully and remove c programs which compilation errors.

Up to now I can only achieve the goal that compiling those 100 programs but I really have no idea how to detect whether there was failed compilation in these 100 programs.

2 Answers2

7

Just check whether the return code is nonzero, and delete the file if it is nonzero. The return code is stored in the shell variable $? after running the compiler.

Here is the long form of what such a script would look like.

for i in {1..99}; 
do
    gcc ${i}.c 2> /dev/null > /dev/null

    if [[ $? -ne 0 ]]; then
        rm ${i}.c
    fi

done

As user268396, the the middle part can be shortened to the following.

gcc ${i}.c || rm ${i}.c

The use of the short-circuiting operator || will ensure that the latter statement will only run if the former statement fails (ie, exits with a non-zero return code).

merlin2011
  • 71,677
  • 44
  • 195
  • 329
0

You can check for the error code that the compiler returns, it is stored in $?

for f in *.c; do
    t=${f%.c}      # Strip the .c from the source file name
    gcc -o $t $f   # Try to compile
    if [[ "$?" -ne 0 ]]; then
        rm $f
    fi
done
chw21
  • 7,970
  • 1
  • 16
  • 31