Linux: copy file with preserving permission

Most of the time the Linux server administrator requires to copy file for backup purpose. If you use the Linux command cp to copy your file, you may need to retain the file permission of source directory at destination directory.

The command is
cp -r --preserve /source_dir /destin_dir

Here -r for copy all inner sub directory, and --preserve for retain the exact file permission.

If you have some files that starts with dot(.) like .htaccess file, those may not copy properly. You can use regular expression to copy those file. Only to copy those files, below is the command
cp -r --preserve /source_dir/.[a-zA-Z0-9]* /destin_dir
OR below one.
cp -r --preserve /source_dir/.\S* /destin_dir

Remember if you use * at regular expression for example as below, it may not work for some people interestingly to move files like .htaccess.
cp -r --preserve /source_dir/.* /destin_dir

Most of the cases the site administrator used to write a Shell/Perl/PHP script that compile the above cp command, and put the script into the cron tab to perform the task as a schedule.

Comments