0

I'm trying to write a system that grades a c++ code with pre-written examples that i have ready. It's a very simple c++ code like the following:

#include <iostream>
using namespace std;
int main()
{
    int a;
    cin >> a;
    if (a > 100)
        cout << "Big";
    else
        cout << "Small";
    return 0;
}

So i want to test and grade this program with a bash, declare a score variable and echo it in the end. Here's what i wrote(I've marked where i need help writing with double quotes)

#!/bin/bash
g++ new.cpp -o new
test1=101
test2=78
score=0
if [ "Result of executing ./new with $test1 variable as input"=="Big" ]
then
(( score += 50 ))
fi
if [ "Result of executing ./new with $test2 variable as input"=="Small" ]
then
(( score += 50 ))
fi
echo $score

Also i'm still very new to bash so if you can tell me a simpler way to use bash for the examples (like loops) i'd love to hear it. Thanks!

3
  • IMHO, using a temporary file would be easier. Your C++ program should write to a temporary file that your bash script can read. Commented Mar 24, 2017 at 20:29
  • Please take a look: shellcheck.net Commented Mar 24, 2017 at 20:30
  • if [ "Result of executing ./new with $test1 variable as input"=="Big" ] is always true, since Result of executing ./new with $test 1 variable as input==Big is a non-empty string. [ is a fickle beast. Commented Mar 24, 2017 at 20:31

1 Answer 1

2

If you want to execute new with the params and get its result, you should try something like this:

#!/bin/bash
g++ new.cpp -o new
test1=101
test2=78
score=0
if [ $(./new $test1) == "Big" ]; then
    (( score += 50 ))
fi
if [ $(./new $test2) == "Small" ]; then
    (( score += 50 ))
fi
echo $score
Sign up to request clarification or add additional context in comments.

2 Comments

You should quote the command substitution $() within [ ], or the script breaks if the output of new contains spaces; the output will also be subject to glob expansion if unquoted.
Alternatively, you could use [[ ]], which does the quoting for you. == is a Bashism anyway, so why not use other Bash tools as well.

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.