A robust Bash script for copying file attributes (ownership, permissions, and SELinux context) from a source file to one or more destination files.
- Copies ownership (user and group)
- Copies permissions (read, write, execute)
- Copies SELinux security context (if SELinux is enabled)
- Provides detailed, color-coded logging
- Handles multiple destination files
- Robust error checking and reporting
- Bash (version 4.0 or later recommended)
- Standard Unix utilities: chown, chmod
- SELinux utilities (optional): getenforce, chcon
-
Download the script file:
wget https://gist.githubusercontent.com/rindeal/bc41ec6232fc80da575104ddb32c19ed/raw/cp-attr.sh
-
Make the script executable:
chmod +x cp-attr.sh
./cp-attr.sh <source_path> <destination_path1> [<destination_path2> ...]
<source_path>
: The file whose attributes you want to copy<destination_path1>
,<destination_path2>
, etc.: One or more files to which you want to apply the attributes
./cp-attr.sh /path/to/source/file.txt /path/to/dest1.txt /path/to/dest2.txt
This command will copy the attributes of file.txt
to both dest1.txt
and dest2.txt
.
The script provides detailed, color-coded output for each operation:
- Blue [INFO]: General information
- Green [SUCCESS]: Successful operations
- Yellow [WARNING]: Non-critical issues
- Red [ERROR]: Critical failures
Example output:
[INFO ] SELINUX | Enabled. Will copy security context.
[INFO ] /path/to/dest1.txt | Starting attribute copy from '/path/to/source/file.txt'
[SUCCESS] /path/to/dest1.txt | change ownership: changed ownership of '/path/to/dest1.txt' from user1:group1 to user2:group2
[SUCCESS] /path/to/dest1.txt | change permissions: mode of '/path/to/dest1.txt' changed from 0644 (rw-r--r--) to 0755 (rwxr-xr-x)
[SUCCESS] /path/to/dest1.txt | change security context: changed security context of '/path/to/dest1.txt'
[SUCCESS] /path/to/dest1.txt | All attributes copied successfully
[INFO ] /path/to/dest2.txt | Starting attribute copy from '/path/to/source/file.txt'
[SUCCESS] /path/to/dest2.txt | change ownership: changed ownership of '/path/to/dest2.txt' from user1:group1 to user2:group2
[ERROR ] /path/to/dest2.txt | Failed to change permissions
[ERROR ] /path/to/dest2.txt | chmod: changing permissions of '/path/to/dest2.txt': Operation not permitted
[WARNING] /path/to/dest2.txt | Some operations failed during attribute copy
[WARNING] SCRIPT | Some operations failed. Please review the log for details.
- The script will continue processing all specified destination files even if operations on one file fail.
- A summary of overall success or failure is provided at the end of the script execution.
- Detailed error messages are displayed for any failed operations.
- Requires appropriate permissions to modify file attributes
- SELinux context copying only works on systems with SELinux enabled
- Does not handle symbolic links specially (attributes are applied to the link itself, not the target)
This project is licensed under the GPL-3.0 License.