Search code examples
bashshell

How to write a bash script that compiles a program, sends output to a log, then checks if the compilation was successful?


I'm trying to make a script with the following goal: on receiving 2 names (1- logfilename, 2- program name), the program should compile the program, and send both outputs to a log.

If successful, then write "compile V" and return 0.
Else "compile X" and return a number.

I tried

#!/bin/bash
    
gcc {$2}.c -Wall -g -o $2> $1 2>&1
exit

I have no idea how to check if it did or didn't succeed and echo V or X.


Solution

  • You can check exit status gcc like this:

    #!/bin/bash
    
    # execute gcc command
    gcc "$2".c -Wall -g -o "$2"> "$1" 2>&1
    
    # grab exit status of gcc
    ret=$?
    
    # write appropriate message as per return status value
    if ((ret == 0)); then echo "compile V"; else echo "compile X"; fi
    
    # return the exit status of gcc
    exit $ret