1

The second input argument($2) is a path to a c program. I need to check if that C program compiles or not.

I believe this is how to compile the C program:

   cc $2

How can the program tell if the C program file compiled or not?

3
  • 5
    Check that $? is equal to 0? Commented Nov 26, 2012 at 18:51
  • Look at the return code and do what you need to do there. Check out a shell tutorial. Commented Nov 26, 2012 at 18:51
  • 1
    Also cc $2 || echo "compilation failed", but then the compiler output would be more helpful. Commented Nov 26, 2012 at 18:54

2 Answers 2

2

Assuming this is a POSIX shell (e.g. Bash), you can either write something like this:

cc "$2"
if [ $? = 0 ] ; then
    # . . . commands to run if it compiled O.K. . . .
else
    # . . . commands to run if it failed to compile . . .
fi

or a bit more tersely:

if cc "$2" ; then
    # . . . commands to run if it compiled O.K. . . .
else
    # . . . commands to run if it failed to compile . . .
fi

In the special case that you simply want to run a certain command if compilation failed, e.g. exit 1, you can write something like:

cc "$2" || exit 1
Sign up to request clarification or add additional context in comments.

2 Comments

will be = or -eq ? I am bit confused
@Omkant: Either way. = is string-equality, -eq is numeric-equality. In this case they both amount to the same thing.
0

In Bash - shell You can directly use the following , no need of if

    cc $2
    [ $? -ne 0 ] && exit 1

    # rest of code 

or you can use,

cc $2
if [ $? -eq 0 ]; then
# code for true
else
# code for false
fi 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.