3

I have a script used in different environments. This scripts uses sudo cp to copy files (sudo otherwise it has no access). But sudo cp creates the files with the wrong owner. It cannot keep the owner of the source files because these to are the wrong ones. Also the owner of the destination directories are different in the locations where this script is used.

Is there a way to sudo cp and set the owner/group to the destination directory owner/group?

4
  • I would invoke chown to set the desired owner to the copied files.
    – vanadium
    Commented Nov 14, 2020 at 11:58
  • That ^^ or don't use cp? Use for instance rsync.
    – Rinzwind
    Commented Nov 14, 2020 at 11:58
  • It is a script, I don't know the owner/group beforehand Commented Nov 14, 2020 at 12:02
  • Just a note when using sudo, it may be better to run sudo on the script file instead of cp. Sudo uses a simple string match on the supplied command, so it's not analyzing the script. It is a balance, what "command" should have sudo rights, but giving sudo rights to cp may cause a lot of harm.
    – user986805
    Commented Nov 14, 2020 at 18:27

3 Answers 3

9

install will give you options to set user/group and mode when copying and creating directories.

sudo install -o user -g group -D -t target/ file1 file2
1
  • The issue is that the owner / group are different in the places were the script is run. So I do not know the user / group beforehand. Commented Nov 16, 2020 at 7:45
5

I've settled with this:

After copying the directory:

sudo cp ${SOURCE_DIR} ${DEST_DIR}

Changing the owner/group with this:

sudo chown "$(stat -c '%U:%G' ${DEST_DIR})" -R ${DEST_DIR}/copied_dir


update 2020-11-16:

Use the --reference option of chown like this:

 sudo chown --reference ${DEST_DIR} -R ${DEST_DIR}/copied_dir
1
  • Yup, works quite well.
    – NKM
    Commented Jul 5 at 14:09
0

Use the --preserve option of cp like this:

sudo cp --preserve /path/to/file /path/to/file2
1
  • The --preserve option of cp retains the original ownership of the source file. By default, cp does what the question asks.
    – Frobozz
    Commented Feb 3, 2023 at 18:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .