Why `sed` does not return exit status if regex does not matched ?

sed does return an exit status:

$ echo "foo" | sed 's/xx/yy/'
foo
$ echo $?
0
$ sed 's/xx/yy/' foo.txt
sed: can't read foo.txt: No such file or directory
$ echo $?
2

Sed's exit codes are about whether the program exited successfully or not, they have nothing to do with the internals of what sed is doing, just with whether or not the command managed to run.

That said, GNU sed does offer a way to do this:

   q [exit-code]
          Immediately  quit  the sed script without pro‐
          cessing any more input, except that  if  auto-
          print  is  not  disabled  the  current pattern
          space will be printed.  The exit code argument
          is a GNU extension.

For example (taken from here):

$  echo "foo"|sed '/foo/ s/f/b/;q'                                                                       
boo
$  echo $?
0
$ echo "trash"|sed  '/foo/{s/f/b/;q}; /foo/!{q100}'
trash
$  echo $?
100

If you wanted to report the fact that any substitution has been successful on any line of the input, you could flag successful substitutions in the hold space and check it on the last line:

seq 6 | sed 's/4/four/;s/5/five/; tm;${x;/1/{x;q};x;q1};b;:m;x;s/.*/1/;x'

tm branches to the m label if any substitution was successful. There, we put 1 in the hold space, which we look for on the last line.


First, all commands, including sed, return an exit status. You are looking for why I wouldn't be returning a failure. Which leads to the second point.

Programs like sed are editors, not predicates. They are there to change data flowing through the program. Error conditions are for conditions like invalid internal commands or a non-existent file on the command-line.

I'm not sure of what logic you want - you don't include any expected output - but this might be what you are looking for:

$ sed '/^test line 7/s//#test line 7/;/^#test line 7/s//& \nAppend New Line/' test.txt
test line 1
test line 2
test line 3
test line 4
test line 5
test line 6
#test line 7
Append New Line

There are other constructs which can handle this as well, for example the b (branch) command in sed.

If you want an actual return code if not found, then you might want to look at gawk and its exit statement.

Tags:

Sed