How to copy files and give them permission of the destination directory

I copy files from source to location. The source does not belong to me, and the permission for the files in the source is rwx ---. The permission of the files copied to the destination directory that belongs to me is ---- rx ---. The destination directory resolution is drwxrwsrwx. How to get files with the same destination directory resolution. I tried "cp --no-preserve = all", but it didn’t work (same resolution anyway).

+7
linux deployment permissions cp
source share
2 answers

Try the following:

cp --no-preserve=mode,ownership $backupfile $destination 
+11
source share

Let me rephrase this to "How to save destination directory permissions on a copy?"
I cannot take responsibility for the answer since I just collected a couple of answers that I found in the wild. So there it is.

At first

Permissions, as a rule, do not apply to the directory into which files are copied, and new permissions are controlled by the umask user . However, when copying a file from one place to another, this is a slightly special case when the umask user is essentially ignored and existing file permissions are preserved.

This explains why you cannot directly distribute src permissions in the dst directory.

However, there is a two-step workaround.

  • cp-metadata : copy the attributes and only the attributes you want to keep in 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 the touch command if you do not want to keep the time stamp. Replace myecho=echo with myecho= to execute the commands.
Keep in mind that this script must run in sudo mode in order to be able to efficiently execute chown and chmod

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

    - save [= ATTR_LIST]
    save specified attributes (default: mode, property, timestamps), if additional attributes are possible: context, links, xattr, all

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

+1
source share

All Articles