You can use qn to quit with exit status n - but to make that useful, you will also need to use some Branching and Flow Control:
t
branch conditionally (that is: jump to a label) only if a s///
command has succeeded since the last input line was read or another
conditional branch was taken.
It is probably best to choose a value for n that is distinct from one of the standard exit status values:
An exit status of zero indicates success, and a nonzero value
indicates failure. GNU 'sed' returns the following exit status error
values:
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.
So for example
$ echo "foo.bar" | sed 's/bar.*$//; t; q42' ; echo $?
foo.
0
whereas
$ echo "foo.bar" | sed 's/baz.*$//; t; q42' ; echo $?
foo.bar
42
If you want to omit the default printing of the pattern space, then replace q
by Q
(note that Q
is a GNU extension).
sed
most certainly does have an exit status, it just doesn't do what you need here. If thesed
command fails, for example, if you try to run it on a file you don't have write access to or one that doesn't exist,sed
will exit with a non-0 exit status. The exit status just indicates whethersed
managed to do what you told it to do, andecho "foo.bar" | sed 's/pop.*$//'
was correctly executed. It deleted all lines withpop
. That there were no such lines is irrelevant, the command still worked. – terdon May 16 '18 at 13:20