将 C++ 程序中的值返回到 bash 脚本中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21197207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning values from a C++ program into a bash script
提问by donnyton
I have a C++ program (on Linux) that computes a double result, and I want to write a bash script that runs the program a variable number of times and averages these results for me. For simplicity, consider the following code:
我有一个计算双重结果的 C++ 程序(在 Linux 上),我想编写一个 bash 脚本,该脚本运行该程序的次数不定,并为我平均这些结果。为简单起见,请考虑以下代码:
main.cpp:
主.cpp:
int main() {
cout << "Some other stuff\n";
double result = foo();
return 0;
}
script.sh:
脚本.sh:
sum = 0
num =
for((i = 0; i < $num; i++)); do
result = ./a.out; #store the result somehow?
sum = $sum + $result
done
avg = $sum / $num
echo "Average: " $avg
Is there an easy way to pass the result of the program back into the bash script? I read about using the exit code, but the return type is a double so I don't think that will work. Parsing the value from string output is unwieldy because the program has other terminal output.
有没有一种简单的方法可以将程序的结果传回 bash 脚本?我阅读了有关使用退出代码的信息,但返回类型是双精度值,因此我认为这行不通。解析字符串输出的值很笨拙,因为程序还有其他终端输出。
回答by that other guy
The UNIX way of doing this is writing non-essential data on stderr and writing the actual result on stdout. That way, you can simply do
UNIX 执行此操作的方法是将非必要数据写入 stderr,并将实际结果写入 stdout。这样,你可以简单地做
int main() {
cerr << "This is output that won't be captured." << endl;
cout << "3.141592" << endl;
}
and use command substitution to capture it:
并使用命令替换来捕获它:
result=$(./a.out)
An uglier way of doing that doesn't require changing the output is to write to another file descriptor:
一种不需要更改输出的更丑陋的方法是写入另一个文件描述符:
int main() {
char* foo = "3.141592\n";
write(42, foo, strlen(foo));
}
This will let you capture the output with:
这将让您捕获输出:
result=$(./a.out 42>&1 > /dev/null)
Note that your shell script has several syntax errors. Try shellcheckto automatically sort out many of them, and feel free to post a question about the issues you can't resolve.
请注意,您的 shell 脚本有几个语法错误。尝试shellcheck自动整理其中的许多,并随时发布有关您无法解决的问题的问题。
回答by vershov
Why don't you use return value as data to your bash script?
为什么不使用返回值作为 bash 脚本的数据?
int main() {
return 46;
}
The output is as follows (yes, it's bash script):
输出如下(是的,它是 bash 脚本):
./a.out ; echo $?
46
In case of double values you could use this approach:
如果是双值,您可以使用这种方法:
#include <iostream>
int main() {
double res = 46.001;
std::cout << res << std::endl;
return 0;
}
And the output:
和输出:
a=`./a.out`; echo $a
46.001