简体   繁体   English

无法读取在 C++ 中运行的 shell 脚本中的变量

[英]Unable to read variables in shell script running in C++

I have a shell script that goes as follows:我有一个 shell 脚本,如下所示:

#!/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.当我直接从命令行运行它时,它会打印“Hello”和我按预期设置的 TESTOUTDIR 变量。

Now I am running this from a C++ program.现在我正在从 C++ 程序运行它。 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?我能做些什么来解决这个问题?

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.我测试了你的代码, TESTOUTDIR变量对我来说打印得很好。 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.我在 Ubuntu 18.04 上用 g++ 7.5.0 测试了你的代码。

My sh executable is a symbolic link to dash , which is a POSIX shell.我的sh可执行文件是到dash的符号链接,它是一个 POSIX shell。 I also tested changing your shebang in test.sh to #!/bin/bash , and I continued to see your TESTOUTDIR printed as expected.我还测试了将test.sh的 shebang 更改为#!/bin/bash ,并且我继续看到您的TESTOUTDIR按预期打印。

I suggest you confirm /test.sh contains the contents you expect.我建议您确认/test.sh包含您期望的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM