Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy files and give them permission of destination directory

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).

like image 670
Nasreddin Avatar asked Dec 17 '15 04:12

Nasreddin


2 Answers

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.

like image 76
laertis Avatar answered Oct 16 '22 22:10

laertis


Try this:

cp --no-preserve=mode,ownership $backupfile $destination
like image 25
Giordano Avatar answered Oct 16 '22 22:10

Giordano