Unable to read variables in shell script running in C++

Viewed 128

I have a shell script that goes as follows:

#!/bin/sh

TESTOUTDIR=/home/speedster/test_dir

echo "Hello"
echo $TESTOUTDIR

When I run this directly from the command line, it prints "Hello" and the TESTOUTDIR variable which I have set as expected.

Now I am running this from a C++ program. My program is as follows:

#include <bits/stdc++.h>
using namespace std;

int main(int argc, char const *argv[]) {
    string runCommand = "/test.sh";
    system(runCommand.c_str());
}

When I run this I get the output as only "Hello". The variable is not getting printed. What can I do to fix this?

1 Answers

This should really be a comment, not an answer, but I don't have enough reputation to comment.

I tested your code, and the TESTOUTDIR variable prints fine for me. Below is what I ran to test your code:

$ cat test.sh
#!/bin/sh

TESTOUTDIR=/home/speedster/test_dir

echo "Hello"
echo $TESTOUTDIR
$ cat test.cpp 
#include <bits/stdc++.h>
using namespace std;

int main(int argc, char const *argv[]) {
    string runCommand = "./test.sh";
    system(runCommand.c_str());
}
$ g++ test.cpp -o test_exec
$ ./test_exec 
Hello
/home/speedster/test_dir

I tested your code on Ubuntu 18.04 with g++ 7.5.0.

My sh executable is a symbolic link to dash, which is a POSIX shell. I also tested changing your shebang in test.sh to #!/bin/bash, and I continued to see your TESTOUTDIR printed as expected.

I suggest you confirm /test.sh contains the contents you expect.

Related