sed -i ... file
actually does something like:
sed ... file > some-temp-file &&
mv some-temp-file file
That last mv
does a rename
. That is sed -i
doesn't edit the file in place, it replaces it with a modified copy of itself.
Here it's the rename that is blocked. It is not blocked because of permission issues (you'd get a permission denied error message if it was), but it looks like there's some administrative restriction either to unlink the inode of your ~/.bash_profile (like some SELinux type of mandatory access control), or to the path to that file (like some AppArmor type MAC).
You can probably find more clue somewhere in the logs.
getfattr -dm- ~/.bash_profile
would list all the extended attributes (ACLs, security contexts) of the file.
lsattr ~/.bash_profile
for potentially more Linux attributes.
I just discovered the reason, and it was a collection of circumstances:
First of all, I don't know exactly why, but sudo
was not grabbing the HOME
environment variable properly and used the one of the regular user, so it read the .vimrc
from /home/user/.vimrc.
In order to see this, I issued:
user@hostname:~$ sudo bash
[sudo] password for user:
root@hostname:/home/user# echo $HOME
/home/user
Second, I have folding persistence enabled in my user's vimrc file in order to store cursor position:
au BufWinLeave * mkview
au BufWinEnter * silent loadview
This makes that every time a file is edited, a properties file is created inside $HOME/.vim/view
folder.
In my case, it looks like I tried to edit the file without sudo
the first time, so the folding file was created as regular user's:
user@hostname:~$ ll .vim/view/ | grep thunderbird.sh
-rw-rw-r-- 1 user user 2650 Aug 20 15:56 =+usr=+lib=+thunderbird=+thunderbird.sh=
Since the root took /home/user
as $HOME
, the same folding file was (wrongly) used when I issued sudo vim
, and for some reason that I ignore, probable related to vim internals, if the folding file is not owned by the editing user, the edited file is opened in ReadOnly mode.
So, I realized that if I removed the file /home/user/.vim/view/=+usr=+lib=+thunderbird=+thunderbird.sh=
and then tried to edit using sudo vim,
I had no problems at all.
So, at the end of the story, in order to fix this situation I just edited /etc/sudoers
and added this line:
Defaults always_set_home
Now everything works as expected and I can use sudo
reliably again.
Best Answer
Yes, the file can be edited.
As far as the directory is concerned, the file can not be edited if you remove the execute permission on the directory for the target (owner/group/others).
EDIT: If you want the owner to not be able to edit the file by changing the permission of the directory (assuming the same user owns the directory and file), then you can simply remove the execute permission on the directory for the owner. For example you can make the permission for the owner as
rw-
i.e.6
.