CentOS文件管理中复制文件的核心命令与技巧
在CentOS系统中,cp(copy) 是复制文件与目录的基础命令,通过不同选项可实现多种复制需求;scp 用于远程复制;rsync 则更适合高效、增量同步。以下是具体用法与注意事项:
cp命令将当前目录下的file.txt复制到/path/to/destination/目录(目标目录需存在):
cp file.txt /path/to/destination/
若目标目录中已有同名文件,cp会直接覆盖(无提示)。
复制file.txt到/path/to/destination/目录,并重命名为new_file.txt:
cp file.txt /path/to/destination/new_file.txt
复制目录dir1/及其所有子目录、文件到dir2/(目标目录需存在):
cp -r dir1/ dir2/
注:-r(recursive)选项是复制目录的关键,否则会提示“omitting directory”(忽略目录)。
复制时保留源文件的权限、所有者、时间戳等属性(适用于备份或迁移):
cp -p important.conf /etc/backup/
-p选项等同于--preserve=mode,ownership,timestamps,确保目标文件与源文件元数据一致。
复制时若目标存在同名文件,先询问是否覆盖:
cp -i source.txt /path/to/destination/
若需强制覆盖(不提示),可加-f(force)选项:
cp -f source.txt /path/to/destination/
rsync命令rsync比cp更适合增量同步(仅复制变化的文件),且支持断点续传、校验文件完整性。
将/source/dir/同步到/destination/dir/(保留属性):
rsync -avh /source/dir/ /destination/dir/
-a:归档模式(递归+保留属性,等同于-rlptgoD);-v:显示详细过程;-h:以人类可读方式显示文件大小。通过--checksum选项强制计算文件校验和(避免因时间戳或大小误判):
rsync -avh --checksum /source/dir/ /destination/dir/
注:此选项会增加传输时间,但确保数据完全一致。
同步时删除目标目录中源目录没有的文件(严格镜像):
rsync -avh --delete /source/dir/ /destination/dir/
scp命令scp(Secure Copy)基于SSH协议,用于本地与远程主机间的文件复制。
将本地local_file.txt复制到远程主机remote_user的/remote/path/目录:
scp local_file.txt remote_user@remote_host:/remote/path/
将远程/remote/path/remote_file.txt复制到本地当前目录:
scp remote_user@remote_host:/remote/path/remote_file.txt .
复制本地local_dir/到远程/remote/path/:
scp -r local_dir/ remote_user@remote_host:/remote/path/
注:-r选项同样用于递归复制目录。
/etc、/usr)需用sudo提权,避免“Permission denied”错误;pwd确认当前目录,避免路径拼写错误;*、?)时,用引号包裹路径(如"my file.txt");md5sum或sha256sum校验源文件完整性,避免传输错误。以上命令覆盖了CentOS中常见的复制场景,根据需求选择合适的工具即可高效完成文件管理任务。