Return value of sed for no match
json, linux, sed
Solution
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.
so if you have:
echo "foo"|sed '/bar/ s/a/b/'
sed will return `0` but if you write some syntax/expression errors, or the input/file doesn't exist, sed cannot execute your request, sed will return 1.
workaround
this is actually not workaround. sed has `q` command: (from man page):
q [exit-code]
here you can define exit-code as you want. For example `'/foo/!{q100}; {s/f/b/}'` will exit with code 100 if `foo` isn't present, and otherwise perform the substitution f->b and exit with code 0.
Matched case:
kent$ echo "foo" | sed '/foo/!{q100}; {s/f/b/}'
boo
kent$ echo $?
0
Unmatched case:
kent$ echo "trash" | sed '/foo/!{q100}; {s/f/b/}'
trash
kent$ echo $?
100
I hope this answers your question.
edit
I must add that, the above example is just for one-line processing. I don't know your exact requirement. when you want to get `exit 1`. one-line unmatched or the whole file. If whole file unmatching case, you may consider awk, or even do a `grep` before your text processing...
Problem
I'm using `sed` for updating my JSON configuration file in the runtime. Sometimes, when the pattern doesn't match in the JSON file, `sed` still exits with return code 0. Returning 0 means successful completion, but why does `sed` return 0 if it doesn't find the proper pattern and update the file? Is there a workaround for that?