JohnnyF
JohnnyF

Reputation: 1101

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.

Upvotes: 0

Views: 4707

Answers (4)

jyvet
jyvet

Reputation: 2201

this code should work :

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

Upvotes: 0

anubhava
anubhava

Reputation: 786011

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

Upvotes: 1

Minh Mai
Minh Mai

Reputation: 216

Try this out:

#!/bin/bash
gcc "$2"".c" -Wall -g -o "$2" 2>&1 >"$1"
#check for error of previous command
if $? ; then echo compile V >>"$1"
else echo compile X >>"$1"; fi
exit

Upvotes: 1

RBH
RBH

Reputation: 592

You can check the success of a program in bash by command $? if echo $? = 0 then success else fail.

Upvotes: 1

Related Questions