[英]Return value from shell script without using echo
I have c++ code which includes a system call which in turn calls a bash oneliner 我有c ++代码,其中包括系统调用,该系统调用又调用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
. 如果我使用
echo
而不是return,我会得到echo
命令的返回码,而不是传递给echo
的值。 Any idea how to go around this? 知道如何解决这个问题吗?
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. 将根据条件返回0或1,
system
会将状态返回给您的C ++代码。
You want to use exit 0
and exit 1
in your bash command. 您想在bash命令中使用
exit 0
和exit 1
。 Note that 0 typically means success, while non-0 means there was some error. 请注意,0通常表示成功,而非0则表示存在一些错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.