Copy files and set owner/group to the owner/group of the destination directory

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?

Asked By: R. Oosterholt


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
Answered By: R. Oosterholt

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
Answered By: user986805

Use the –preserve option of cp like this:

sudo cp --preserve /path/to/file /path/to/file2
Answered By: jinliming2