13

I am copying files from source to location. The source is not owned by me and the permission for files at source is ----rwx---. The permission of files coped to destination directory which is owned by me is ----r-x---. The permission of destination directory is drwxrwsrwx. How do I have the files with same permission of destination directory. I tried "cp --no-preserve=all" but it did not work (still the same permission).

laertis
  • 8,229
  • 4
  • 21
  • 17
Nasreddin
  • 1,509
  • 9
  • 31
  • 36

2 Answers2

12

Try this:

cp --no-preserve=mode,ownership $backupfile $destination
Giordano
  • 5,422
  • 3
  • 33
  • 49
  • 5
    This does _not_ set the destination directory's permissions on newly copied files. Instead, it sets permissions of the user under which copy operation is done. For example, if you copy under root, copied files permissions will be `root:root`. – o.v Mar 28 '18 at 09:09
5

Let me rephrase that to "How to preserve permissions of destination directory on copy?"
I can't take credit for the answer since I just combined a couple of answers I found on the wild. So here it comes.

Firstly

Permissions are generally not propagated by the directory that files are being copied into, rather new permissions are controlled by the user's umask. However when you copy a file from one location to another it's a bit of a special case where the user's umask is essentially ignored and the existing permissions on the file are preserved.

Which explains why you can't directly propagate the permissions of the src to the dst directory.

However, there is two-step workaround to this.

  1. cp-metadata: Copy the attributes and only the attributes you want to preserve back to the source directory. Here is a quick script that can do this:
#!/bin/bash
# Filename: cp-metadata

myecho=echo 
src_path="$1"  
dst_path="$2"

find "$src_path" |
  while read src_file; do
    dst_file="$dst_path${src_file#$src_path}"
    $myecho chmod --reference="$src_file" "$dst_file"
    $myecho chown --reference="$src_file" "$dst_file"
    $myecho touch --reference="$src_file" "$dst_file"
  done

You can leave out the touch command if you don't want keep the timestamp. Replace myecho=echo with myecho= to actually perform the commands.
Mind that this script should be run in sudo mode in order to be able to run chown and chmod effectively

  1. cp --preserve: After you have successfully run the first command now it's time to copy the contents along with the attributes to the dst directory.

    --preserve[=ATTR_LIST]
    preserve the specified attributes (default: mode,ownership,timestamps), if possible additional attributes: context, links, xattr, all

    \cp -rfp $src_dir $dst_dir should do what you want.

Community
  • 1
  • 1
laertis
  • 8,229
  • 4
  • 21
  • 17