0

I have c++ code which includes a system call which in turn calls a bash oneliner

if (system("if [ `ls | wc -l` -eq 1 ]; then return 0 ; else return 1; fi") != 0)
    std::cout << "returned non zero" << std::endl;
else
    std::cout << "returned zero" << std::endl;

This doesn't work since I get this error

-bash: return: can only `return' from a function or sourced script

If I use echo instead of return I get the return code of the echo command instead the value passed to echo. Any idea how to go around this?

2
  • It would be far simpler to just open the current working directory in C++ than to shell out to bash to launch yet more programs. Commented Feb 4, 2014 at 19:26
  • This code is just to demonstrate my problem, the "if" statement in my system call is much more complex Commented Feb 5, 2014 at 10:14

2 Answers 2

2

You don't really need return, just change your code to this:

if ( system( "[ `ls | wc -l` -eq 1 ]" ) != 0)
    std::cout << "returned non zero" << std::endl;
else
    std::cout << "returned zero" << std::endl;

This code:

[ `ls | wc -l` -eq 1 ]

will return 0 or 1 as per the condition and system will return that status to your C++ code.

Sign up to request clarification or add additional context in comments.

Comments

1

You want to use exit 0 and exit 1 in your bash command. Note that 0 typically means success, while non-0 means there was some error.

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.