13

When I use sudo to do some activities with files, these files change ownership. How can I use commands with sudo without changing owner of the files?

Example file archivos35.sh is from apache but I use sed (with usr admin sudo)

$ ls -l
-rwxr-xrw-. 1 apache apache 181 Aug 5 11:56 archivos35.sh

User admin with sudo ---

sudo sed -i s/old/new/g archivos35.sh

But doing that command with sudo changes the owner of the file

$ ls -l
-rwxr-xrw-. 1 admin apache 181 Aug 5 11:56 archivos35.sh

How can I avoid using the command with sudo to change the owner of the file? I just want to make changes to the file without modifying its owner.

muru
  • 69,900
  • 13
  • 192
  • 292
Dok Gus
  • 131
  • 1
  • 3

2 Answers2

30

If you need to use sudo to modify the file, then use it to switch to the right user. You don't need to switch to root, that's just the default. So, in your case, you'd want to do:

sudo -iu apache sed -i 's/old/new/g' archivos35.sh

That will run the sed command as the user apache.

ilkkachu
  • 133,243
  • 15
  • 236
  • 397
terdon
  • 234,489
  • 66
  • 447
  • 667
2

You're not really changing the ownership of the file, rather you're removing the old file and creating a new one. When you do that the new file is created owned by the uid of the creator. To avoid this you must modify the file in place. Edit it using a text editor that saves by overwriting the original file in place. Or run your sed commands with output to a temp file and then copy the temp file over the original file.

Kyle Jones
  • 14,845
  • 3
  • 40
  • 51
  • 1
    You would think that the `-i` option aka `--in-place` would actually modify inplace... – JShorthouse Aug 05 '19 at 16:25
  • Whit The @teldon response, I managed to do what I need. with sed I modify the place without opening the file. – Dok Gus Aug 05 '19 at 17:42
  • 1
    @JShorthouse You'd think, but it doesn't, at least not everywhere. – Kyle Jones Aug 05 '19 at 17:50
  • 3
    @JShorthouse most so-called 'in-place' edits aren't, they mostly change a temporary file and then mv it over the original (and that includes most, if not all, implementations of sed. and perl. and most other programs with an "in-place edit" option). If you want actual in-place editing, use a scriptable text editor like `ed` or `ex` or `vi`/`vim`. – cas Aug 06 '19 at 02:41
  • 1
    Even some text editors use the temp+rename method when writing the file, as a fail-safe in case of a crash while writing. E.g. Emacs does this by default, but you can overwrite it with configuration. – Barmar Aug 06 '19 at 16:01
  • I always thought that `-i` meant "interactive" – jocull Aug 06 '19 at 16:56