【问题标题】:sed is not showing exit status as other linux commandssed 没有像其他 linux 命令一样显示退出状态
【发布时间】:2013-10-27 01:02:14
【问题描述】:
$ cat file 
aa
Baa
CaaD
$ sed -i -e 's/aa/AA/' file
$ echo $?
0
$ cat file
AA
BAA
CAAD
$ sed -i -e 's/aa/AA/' file
$ echo $?
0

无论是否修改,这两种情况下的 sed 命令退出状态都是相同的,并且它返回与 0 相同的退出状态。如果它更改,我希望它为 0,如果没有修改,我希望它为 1任何东西。

如果 grep 命令在找到某个字符串时返回 0,如果没有则返回 1,同样的方式,如果 sed 命令修改了文件,它必须返回 0,而 sed 命令没有修改任何内容,则它必须返回 1

我尝试使用 sed internal 'q' 命令,但没有帮助。请帮帮我。

【问题讨论】:

  • 但是这里没有错误。我希望 sed 在无法读取文件或使用无效模式调用文件时返回错误,但在没有完成替换时不会返回错误。
  • 作为Kent comments, as @cnicutar commented, the return code of a command means if the command was executed successfully. has nothing to do with the logic you implemented in the codes/scripts
  • “它必须”——谁说的?
  • 查看 grep 命令是否在找到某个字符串时返回 0,如果没有则返回 1,同样的方式,如果 sed 命令修改文件,它必须返回 0,而 sed 命令不修改任何内容然后它必须返回 1。

标签: linux bash shell sed exit-code


【解决方案1】:

答案是“因为这就是 sed 的实现方式”

如果您想查看是否进行了任何更改

sed -i.bak -e 's/aa/AA/' file
if diff -q file file.bak >/dev/null; then
    echo no changes
else
    echo something changed
fi

【讨论】:

  • 好的,在这种情况下,我可以使用简单的 grep 来处理我的情况。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-20
  • 2014-01-24
  • 2011-06-21
  • 2021-10-29
  • 2021-05-31
  • 2018-09-18
相关资源
最近更新 更多