简体   繁体   English

$?中的命令行perl错误值不正确?

[英]Incorrect command-line perl error value in $?

I am using command-line perl to perform a inplace substitution in a file. 我正在使用命令行perl在文件中执行就地替换。 This is the code: (note the root perm with sudo) 这是代码:(注意sudo的根权限)

sudo perl -i -pe "s/foo/bar/" config.txt

If this succeeds, 'echo $?' 如果成功,则回显$? return 0. Now I make the file un-writable even for root using chattr like this: 返回0。现在我使用chattr使文件即使对于root也无法写:

sudo chattr +i config.txt

I run the same perl command and it fails with this error: 我运行相同的perl命令,但失败并显示以下错误:

Can't remove config.txt: Operation not permitted, skipping file. 无法删除config.txt:不允许操作,正在跳过文件。

Which is fine. 没关系 However, 'echo $?' 但是,“ echo $?” still returns 0 in this case. 在这种情况下仍返回0。 Why is this so? 为什么会这样呢? Shouldn't it return a non-zero value indicating an error? 它不应该返回表示错误的非零值吗?

The problem is that Perl does not come back with a non-zero exit status for this condition ( sudo passes on the exit status of the command it was given), which is a bit vexing. 问题在于,在这种情况下,Perl不会返回非零退出状态( sudo传递了给出命令的退出状态),这有点烦人。 You can work around the problem by recognizing that the line-reading loop is never entered if the file fails to be renamed and handle it with a flag: 您可以通过以下方法解决该问题:识别出如果文件重命名失败,则永远不会进入行读取循环,并使用标志进行处理:

sudo perl -i -ne 's/foo/bar/; print; $wrk = 1; }{ $wrk or exit 1' config.txt

The Eskimo greeting (or butterfly) "operator" }{ introduces an END block, in a way; 爱斯基摩人问候语(或蝴蝶语)“ operator” }{在某种程度上引入了END块; what comes after it is executed when the loop reading lines from the file has ended. 从文件中读取循环行结束时执行该命令后的结果。 The way it works is described here . 这里描述它的工作方式。

The caveat is that this will also report an error if config.txt is empty. 需要注意的是,如果config.txt为空,这也会报告错误。 A shorter if a bit hackier way is to use the special $. 如果使用骇客的话,一种更短的方法是使用特殊的$. line counter variable for the same purpose: 出于相同目的的行计数器变量:

sudo perl -i -ne 's/foo/bar/; print; }{ $. or exit 1' config.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM