Pages

Tuesday, 12 May 2020

Be careful with 'sed -i' and vim's "w!"

1. Example

$ ls -ld /tmp/test
drwxrwxrwx. 2 user01 user01 21 May 12 17:21 /tmp/test
$ ls -l /tmp/test/
total 4
-rw-r--r--. 1 user01 user01 16 May 12 16:50 sed.txt

2. Vim's "w!"

Here the file sed.txt is not writable to user01. If user02 tries to edit it via an editor like vim, an error will occur like.

# login as user02
vim /tmp/test/sed.txt

E45: 'readonly' option is set (add ! to override) 
if trying to save it via "w!" command, it would actually create a new file and delete the old one.

# save with "w!" in vim
ls -l /tmp/test/sed.txt
-rw-r--r--. 1 user02 user02 23 May 12 17:30 sed.txt

As a result, the new file with the same name as the old one was created. It looks like changing the old file, but it has side effects: the metadata (owner here) is now changed

3. sed -i

The man page of 'sed' says:

-i[SUFFIX], --in-place[=SUFFIX]

              edit files in place (makes backup if SUFFIX supplied)

But it's not accurate! The operation just looks like "in place", but it actually creates a new file and deletes the old one.

# login as user02
$ ls -l sed.txt
-rw-r--r--. 1 user01 user01 23 May 12 17:30 sed.txt

$ sed -i 's/h/H/' sed.txt
$ ls -l sed.txt
-rw-r--r--. 1 user02 user02 23 May 12 17:31 sed.txt

We can see that 'sed -i' created a new file owned by user02.

4. Thought of "modify"

Here we can see two methods to change files's content:
  1. Modify a file directly (in place)
  2. Create a new file with modified content of the old file, then delete the old one, then rename the new file as the old file's name.
We can check out what really happened by looking at the inode via "ls -i". If the inode number changed, it means a new file was created and the old one was removed.

[user02@cf-31 test]$ ls -li sed.txt
747194 -rw-r--r--. 1 user01 user01 23 May 12 17:40 sed.txt
[user02@cf-31 test]$ sed -i 's/1/2/' sed.txt
[user02@cf-31 test]$ ls -li sed.txt
747191 -rw-r--r--. 1 user02 user02 23 May 12 17:50 sed.txt

Even though the new content is what we wanted, the metadata like the owner, permissions may be different to the old file as well. And the different metadata may cause issues!!! (e.g. the new file may not be readable to some users who can do it before).




No comments:

Post a Comment