1
$ 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

This sed command exit status in both the cases whether it modifies or not is same and it is returning the same exit status as 0. I would like to have it as 0 if it changes and 1 in case if haven't modified anything.

If grep command return 0 if it found some string and return 1 if it does not , Same way if sed command modifies the file it has to return 0 and sed command doesn't modify anything then it has to return 1

I tried to use sed internal 'q' command but it didn't helped. Please help me.

Sriharsha Kalluru
  • 1,743
  • 3
  • 21
  • 27
  • 1
    possible duplicate of [Return code of sed for no match](http://stackoverflow.com/questions/15965073/return-code-of-sed-for-no-match) – fedorqui Oct 18 '13 at 08:51
  • But there's no error here. I'd expect sed to return an error when the file could not be read or it's called with an invalid pattern, but not when no replacement is done. – Axel Oct 18 '13 at 08:52
  • 2
    As [Kent comments](http://stackoverflow.com/a/15965681/1983854), `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` – fedorqui Oct 18 '13 at 08:54
  • "It has to" -- says who? – n. m. could be an AI Oct 18 '13 at 09:31
  • 1
    See if grep command return 0 if it found some string and return 1 if it does not , Same way if sed command modifies the file it has to return 0 and sed command doesn't modify anything then it has to return 1. – Sriharsha Kalluru Oct 18 '13 at 09:39
  • possible duplicate of [How to check if the sed command replaced some string?](http://stackoverflow.com/questions/15433058/how-to-check-if-the-sed-command-replaced-some-string) – n. m. could be an AI Oct 18 '13 at 10:30
  • Why do you think, that no-match-found == sed has failed? – anishsane Oct 18 '13 at 13:58

1 Answers1

1

The answer is "because that's how sed is implemented"

If you want to see if any changes were made

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
glenn jackman
  • 238,783
  • 38
  • 220
  • 352