如何在管道命令行中使用第一个程序的返回码 [英] How to use the return code of the first program in a pipe command line
问题描述
我正在编写一个简单的程序,该程序可以解析编译器的输出并重新格式化任何错误消息,以便我们使用的IDE(Visual Studio)可以解析它们.我们使用nmake
进行构建,它将使用如下命令行来调用编译器:
I'm writing a simple program that parses the output from a compiler and reformats any error messages so that the IDE we use (visual studio) can parse them. We use nmake
to build, and it will call the compiler using a command line like this:
cc166.exe SOME_FLAGS_HERE MyCFile.c 2>&1 | TaskingVXToVisualReformat.exe
现在的问题是,编译器的返回代码cc166
没有反馈给nmake
.仅使用重新格式化程序的返回代码,这意味着如果我从重新格式化程序返回零,则nmake将继续构建而不是中止.如何将编译器(cc166.exe
)的返回代码反馈到nmake
?
Now the problem is that the return code of the compiler, cc166
, is not fed back to nmake
. Only the return code of my reformatter is used which means that if I return zero from the reformat program, nmake will continue to the build instead of aborting. How can I feed back the return code from the compiler (cc166.exe
) to nmake
?
重新格式化程序可以通过任何方式读取编译器的返回代码,并在决定其自身的返回代码时使用它吗?重新格式化程序是用C#编写的.
Is there any way my reformat program can read the return code of the compiler and use that when deciding its own return code? The reformatter is written in C#.
推荐答案
我将编译指令放在bash脚本中,并利用其pipefail功能:
I would put the compilation instructions in a bash script and make use of its pipefail feature:
管道的退出状态是管道中最后一个命令的退出状态,除非启用了pipefail选项.如果启用了pipefail,则管道的返回状态是最后一个(最右边的)命令的值(非零状态);如果所有命令成功退出,则返回零.
让我们通过一个简单的测试来尝试一下:
Let's try it with a simple test:
$ cat bash_pipe.sh
#!/bin/bash
set -o pipefail
ls $1 2>&1 | perl -ne '{print;}'
如果我们使用现有文件运行它,则退出代码将为0(通过管道传递):
If we run it with an existing file, the exit code is going to be 0 (passed through the pipe):
$ ./bash_pipe.sh bash_pipe.sh
bash_pipe.sh
$ echo $?
0
另一方面,命令因文件不存在而失败:
On the other side the command fails with an inexistent file:
./bash_pipe.sh inexistent
ls: cannot access inexistent: No such file or directory
echo $?
2
因此,在您的情况下,您需要将编译指令放入类似的脚本中
So in your case you'd need to put the compilation instructions in a script like
$ cat compilation_script.sh
#!/bin/bash
set -o pipefail
cc166.exe SOME_FLAGS_HERE $1 2>&1 | TaskingVXToVisualReformat.exe
并直接(如果可以的话)或通过
and call it directly (if you can) or indirectly through
bash -c "compilation_script.sh MyCFile.c"
注意:pipefail选项是在bash版本3中引入的.
Note: the pipefail option was introduced in bash version 3.
这篇关于如何在管道命令行中使用第一个程序的返回码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!