本文介绍了外壳中的状态码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在重构Python脚本时,我使用Makefile(在Linux下运行GNU make)来自动化我的笨拙工作.该脚本创建了一个输出文件,在进行重构时,我想确保该输出文件保持不变.

I use a Makefile (with GNU make running under Linux) to automate my grunt work when refactoring a Python script.The script creates an output file, and I want to make sure that the output file remains unchanged in face of my refactorings.

但是,我发现没有办法获得命令的状态码来影响后续的shell if命令.

However, I found no way to get the status code of a command to affect a subsequent shell if command.

以下规则说明了该问题:

The following rule illustrates the problem:

check-cond-codes:
    diff report2008_4.csv report2008_4.csv-save-for-regression-testing; echo no differences: =$$!=
    diff -q poalim report2008_4.csv; echo differences: =$$!=

第一个'diff'比较两个相等的文件,第二个'diff'比较两个不同的文件.输出为:

The first 'diff' compares two equal files, and the second one compares two different files.The output is:

diff report2008_4.csv report2008_4.csv-save-for-regression-testing; echo no differences: =$!=
no differences: ==
diff -q poalim report2008_4.csv; echo differences: =$!=
Files poalim and report2008_4.csv differ
differences: ==

显然是"$$!"是错误的变量,无法捕获状态代码"diff".即使使用 外壳:=/bin/bashMakefile开头没有解决问题.

So obviously '$$!' is the wrong variable to capture the status code of 'diff'.Even using SHELL := /bin/bashat beginning of the Makefile did not solve the problem.

在实际规则中,如果需要的话,将返回一个需要该值的变量(如果根本存在).

A variable returning the value, which I need, would (if it exists at all) be used in an 'if' command in the real rule.

不希望创建一个小型的临时shell脚本来代替在Makefile中内联编写所有命令,但是我将把它用作最后的选择.

The alternative of creating a small ad-hoc shell script in lieu of writing all commands inline in the Makefile is undesirable, but I'll use it as a last resort.

相关:

推荐答案

我认为您正在寻找$? shell变量,该变量提供了上一条命令的退出代码.例如:

I think you're looking for the $? shell variable, which gives the exit code of the previous command. For example:

$ diff foo.txt foo.txt
$ echo $?
0

要在生成文件中使用它,必须像$$?中那样转义$:

To use this in your makefile, you would have to escape the $, as in $$?:

all:
    diff foo.txt foo.txt ; if [ $$? -eq 0 ] ; then echo "no differences" ; fi

请注意,make中规则主体中的每个命令都在单独的子shell中运行.例如,以下操作将不起作用:

Do note that each command in your rule body in make is run in a separate subshell. For example, the following will not work:

all:
    diff foo.txt foo.txt
    if [ $$? -eq 0 ] ; then echo "no differences" ; fi

因为diffif命令在不同的Shell进程中执行.如果要使用命令的输出状态,则必须在相同的shell上下文中使用,如我的上一个示例一样.

Because the diff and the if commands are executed in different shell processes. If you want to use the output status from the command, you must do so in the context of the same shell, as in my previous example.

这篇关于外壳中的状态码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 13:14
查看更多