12

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.

  • Why is your script world-writeable? – Jim L. Aug 5 '19 at 16:38
  • By mistake I set it with 756. I shouldn't – Dok Gus Aug 5 '19 at 17:37
29

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.

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.

  • 1
    You would think that the -i option aka --in-place would actually modify inplace... – JShorthouse Aug 5 '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 5 '19 at 17:42
  • 1
    @JShorthouse You'd think, but it doesn't, at least not everywhere. – Kyle Jones Aug 5 '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 6 '19 at 2: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 6 '19 at 16:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.