使用sed命令时如何获取退出状态?

Modified on: Thu, 14 Jun 2018 07:02:23 +0800

grep命令给出退出状态:

$echo "foo.bar" | grep -o foo
foo
$echo $?
0
$echo "foo.bar" | grep -o pop
$echo $?
1  

但我需要使用sed,我意识到它没有退出状态:

$echo "foo.bar" | sed 's/bar.*$//'
foo.
$echo $?
0
$echo "foo.bar" | sed 's/pop.*$//'
foo.bar
$echo $?
0  

我知道我应该使用-q选项,但我还没有成功。

最佳答案

您可以使用q n 退出退出状态 n - 但要使其有用,您还需要使用一些分支和流量控制

  


  有条件地分支(即:跳转到标签)只有s///
  自从读取了最后一个输入行或另一个输入行以来,命令已成功
  采取了条件分支。

最好为 n 选择一个与标准退出状态值不同的值:

  

退出状态为零表示成功,非零值
  表示失败。 GNU'sed“返回以下退出状态错误
  值:

0 Successful completion. 1 Invalid command, invalid syntax, invalid regular expression or a GNU 'sed' extension command used with '--posix'. 2 One or more of the input file specified on the command line could not be opened (e.g. if a file is not found, or read permission is denied). Processing continued with other files. 4 An I/O error, or a serious processing error during runtime, GNU 'sed' aborted immediately.

所以例如

0
 Successful completion.

1
 Invalid command, invalid syntax, invalid regular expression or a
 GNU 'sed' extension command used with '--posix'.

2
 One or more of the input file specified on the command line could
 not be opened (e.g.  if a file is not found, or read permission is
 denied).  Processing continued with other files.

4
 An I/O error, or a serious processing error during runtime, GNU
 'sed' aborted immediately.

,而

$ echo "foo.bar" | sed 's/bar.*$//; t; q42' ; echo $? 
foo.
0

如果要省略模式空间的默认打印,则用q替换Q(注意Q是GNU扩展名)。

作者:,steeldriver

相关问答

添加新评论