I want to edit a file "in place", preserving the file's permissions, yet be safely re-runnable should an interruption occur at any time. Though the script does not need to be multi-user safe, I am vaguely interested in how that might be achieved (I guess with file locking). I know about Perl's -i switch, but this switch first renames the file, so if the user CTRL-C's (or power is lost) after the rename but before the new file is written, the script is not re-runnable because the original file has been renamed (or may not be complete). Is that right? Anyway, here is my attempt at solving this problem.
# Slurp file $fname into array @lines. open(my $fh, $fname) or die "open '$fname': $!"; my @lines = <$fh>; close($fh); # Mangle @lines as appropriate ... if ($file_contents_changed) { my $bak = $fname . $$ . '.tmp'; open(my $fh, '>'.$bak) or die "create $bak: $!"; print $fh @lines or die "writing $bak: $!"; close($fh) or die "close $bak: $!"; defined(my $mode = (stat($fname))[2]) or die "stat $fname: $!"; -w _ or (chmod($mode|0200, $fname) or die "chmod $fname: $!"); rename($bak, $fname) or die "rename $bak $fname: $!"; chmod($mode, $fname) or die "chmod $fname: $!"; }
This has at least one flaw. In the case of a read-only file, if you are interrupted after chmod($mode|0200) but before chmod($mode), the file $fname will have the wrong permissions on re-run. Improvements welcome.
References Added Later
In reply to Re-runnably editing a file in place by eyepopslikeamosquito
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |