It depends on the editor.
It's entirely possible for a text editor to check the permissions on the file, and refuse to write to it if it doesn't have write permissions for either owner, group, or others. Just because it can write to a file (because it's running as root), that doesn't mean it has to.
I just tried this with vim 7.3 on Ubuntu, and it actually does do this. If I edit a file as root, it sets it to readonly mode. (I can still write to it by using :w!
rather than :w
.) GNU Emacs 23.2.1 behaves similarly.
nano, as you observe, doesn't do this; I haven't tried other editors. But nano -v
edits a file in "view" (read-only) mode. It shouldn't be too difficult to write a wrapper that checks the permissions on a file and invokes either nano
or nano -v
, depending on whether it should be writable. (Note that you'd need to use something other than the [ -w filename ]
test; if you're root, it returns true for a file with 400 permissions.)
EDIT :
Here's a nano
wrapper I just threw together in Perl. It doesn't accept any arguments other than a single file name, which is mandatory (and the file must already exist).
#!/usr/bin/perl
use strict;
use warnings;
die "Usage: $0 file\n" if scalar @ARGV != 1;
my $file = $ARGV[0];
die "$file does not exist\n" if not -e $file;
my @stat = stat $file;
die "stat $file: $!\n" if not @stat;
my $mode = $stat[2];
my @command = qw(nano);
if (($mode & 0222) == 0) {
push @command, '-v';
}
push @command, $file;
# print "\$ @command\n";
exec @command;
Rather than checking whether the file is writable, it retrieves its mode bits and directly checks whether any of the write bits are set. It seems to work with the very cursory testing I did. Use this at your own risk. It should be easy to adapt to other editors.
BTW, I never use nano myself. It seems that when you quit, it asks whether you want to save the modified buffer and prompts for the file to save it to, even if the file is writable. At least in its default mode, it seems to me that it would be difficult to accidentally clobber a file. I suppose it's easier if you set some options for "expert" use.
thanks for the ideas. I'll have a look at a few editors. I'd appreciate a few more details on the nano wrapper too, if you can. – MountainX – 2012-03-27T00:15:44.593
Thanks for your excellent answer. Sorry it took me a few weeks to accept it. – MountainX – 2012-06-28T02:48:13.450