How to use the return code of the first program in a pipe command line

泄露秘密 提交于 2019-12-03 14:17:41

I would put the compilation instructions in a bash script and make use of its pipefail feature:

The exit status of a pipeline is the exit status of the last command in the pipeline, unless the pipefail option is enabled. If pipefail is enabled, the pipeline’s return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully.

Let's try it with a simple test:

$ cat bash_pipe.sh
#!/bin/bash
set -o pipefail
ls $1 2>&1 | perl -ne '{print;}'

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"

Note: the pipefail option was introduced in bash version 3.

You can separate your single command into two and keep compilation results in a temporary file:

cc166.exe SOME_FLAGS_HERE MyCFile.c > CCRESULT.TXT 2>&1
if not errorlevel 1 TaskingVXToVisualReformat.exe < CCRESULT.TXT
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!