sed -i destroys symlink

Bug #367211 reported by Miek Gieben
10
This bug affects 1 person
Affects Status Importance Assigned to Milestone
sed (Ubuntu)
Fix Released
Undecided
Unassigned

Bug Description

When using 'sed -i' on a symlink the symlink gets destroyed.
Observe:

% ls -l myfile symlink
-rw-rw-r-- 1 miekg miekg 12 Apr 26 10:53 myfile
lrwxrwxrwx 1 miekg miekg 6 Apr 26 10:53 symlink -> myfile

# do an edit
% sed -i 's/hello//' symlink

% ls -l myfile symlink
-rw-rw-r-- 1 miekg miekg 12 Apr 26 10:53 myfile
-rw-rw-r-- 1 miekg miekg 7 Apr 26 10:54 symlink

And gone is your symlink.

This either a feature or a bug :)

Revision history for this message
Miek Gieben (miek) wrote :

This is due to using rename(), in the file lib/utils.c (is sed's source) at line 324 in the function:
ck_rename (from, to, unlink_if_fail):

       int rd = rename (from, to);

from is now a tmp-file and to is the original file. According to the manpage of rename(2):

       If oldpath refers to a symbolic link the link is renamed; if newpath refers to a symbolic link
       the link will be overwritten.

So the later thing happens.

Revision history for this message
Miek Gieben (miek) wrote :

The following "patch" fixed the problem. It does so by looking at the target. If it is an symlink the tmp file will be copied
to the target of the symlink. Patch also included as attachment.

elektron.m% diff -ur sed-4.1.5/lib/utils.c sed-4.1.5-modified/lib/utils.c
--- sed-4.1.5/lib/utils.c 2005-06-21 16:09:40.000000000 +0200
+++ sed-4.1.5-modified/lib/utils.c 2009-04-27 11:04:38.003830559 +0200
@@ -321,7 +321,19 @@
   const char *from, *to;
   const char *unlink_if_fail;
 {
- int rd = rename (from, to);
+ /* if to is a symlink, shouldn't we move the the link name instead? */
+ char *buf[255];
+ int rd;
+ ssize_t sym;
+ if ((sym = readlink(to, buf, 254)) != -1)
+ {
+ buf[sym] = '\0';
+ rd = rename (from, buf);
+ }
+ else
+ {
+ rd = rename (from, to);
+ }
   if (rd != -1)
     return;

Revision history for this message
Paolo Bonzini (bonzini) wrote :

sed 4.2 will provide --follow-symlinks, for now it is a feature that you cannot turn off. Sorry.

Revision history for this message
Paolo Bonzini (bonzini) wrote :

Fixed in karmic thanks to update to sed-4.2.1

Changed in sed (Ubuntu):
status: New → Fix Released
Revision history for this message
Aditya Gnaneshwar (aditya-28041991) wrote :

can we have a similar option for a hard link file?

To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.