简体   繁体   English

从Shell脚本返回值而不使用echo

[英]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 0exit 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.

相关问题 通过shell脚本检查C ++可执行文件的返回值 - Checking return value of a C++ executable through shell script 如何从 shell 脚本中获取 echo 语句以及执行状态到 c++ 程序中 - how to get the echo statements as well as execution status from a shell script into a c++ program 使用 Main() 返回值作为 python 脚本的参数 - Using Main() return value as an argument for a python script 使用子进程从 C++ 程序到 Python 脚本获取返回值 - Get a return value from C++ program to a Python script using subprocess 如何在不使用 c++ 中的“return”的情况下使用返回值退出 function - How to exit a function with a return value without using "return" in c++ 如何在不使用Future标头的情况下从线程返回值? - How can I return a value from a thread without using the future header? 使用Shell脚本中的-D名称编译选项 - Using the -D name compilation option from a shell script 从shell调用脚本和使用system()有什么区别? - What is the difference between calling a script from the shell and using system()? 如何在不使用C ++ / C的阻塞函数的情况下将值从线程返回到主函数 - How to return value from the thread back to main function without using blocking function in C++/C 如何从C ++代码启动的批处理/ shell脚本中获取返回代码 - How to get the return code from a batch/shell script that launched from C++ code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM