2010/3/12 ????? ???????????? <olga.kryzhanovska at gmail.com>: > This one, right? > ? ? ? -i[SUFFIX], --in-place[=SUFFIX] > ? ? ? ? ? ? ?edit files in place (makes backup if extension supplied) > > -i copies the content to a temporary backup file, truncates the > original (keeping permissions, ACL flags etc) and starts processing > from backup to original file, right?
This algorithm can introduce race conditions which could result in security problems and in disk full conditions can result in a partially written file. A better approach would be the equivalent of: 1. ln $file $file.$suffix 2. newfile=$(mktemp $(dirname $file)/$(basename $file).XXXXXX 3. chown $user:$group $newfile 4. chmod $perms $newfile ; # plus more magic to do extended attributes 5. sed $sedprog $file > $newfile 6. rename $newfile $file Important points of the above are: 1. Takes no space (aside from a directory entry), preserves permissions 2. Secure creation of a temporary file in the same directory as the file to ensure that rename(2) works. If a symlink is involved, this should be done in the directory where the file really exists. 3 - 4. Sets the permissions properly. Use the same code or algorithm that cp -p@ uses. 5. What sed normally does 6. An atomic operation, leaves $file.$suffix as the backup file. Any error in 1 - 5 should cause the initial file to be untouched (aside from maybe atime and nlink), allowing sed to return an error without data loss. -- Mike Gerdts http://mgerdts.blogspot.com/