![查看所有 Bash/Shell 脚本相关的常见问题解答](https://www.alaica.com/wp-content/uploads/linux-125.png)
我是一名 Linux 新用户。我使用scp将文件上传到net-storage提供的CDN公司。我不想覆盖现有文件。在 Linux、Mac OS X 或类 Unix 操作系统下使用 scp 命令时如何防止文件被覆盖?
简短的回答——不可能。
教程详情 | |
---|---|
难度级别 | 简单的 |
根权限 | 不 |
要求 | 同步 |
美东时间。阅读时间 | 2分钟 |
长答案
如果所有者具有写入权限,该scp命令将始终覆盖已存在的文件。我建议你使用该rsync命令。语法是
rsync --ignore-existing file1 user @ server1: / dest / rsync --ignore-existing file.to.upload user@server1.example.com : / path / to / dest / ###添加ssh,以防万一; ) ### rsync -e ssh --ignore-existing file.to.upload user@server1.example.com : / path / to / dest / rsync -avP --ignore-existing * .png user@server1.example . com : /stoage/static/c/example.com/images/rsync --ignore - existing file1 / path / to / dest /
该--ignore-existing选项跳过更新接收器上存在的文件,例如 server1.example.com。
外壳脚本示例
以下脚本将使用 rsync 命令将文件从您的计算机上传到远程服务器。首先,确保设置公钥身份验证:
#!/bin/bash # 目的:从我的桌面批量文件上传到远程服务器 # 作者:GPL v2.x+ 下的 example <www.example.com> # -------------- -------------------------------------------------- - _server = “server1.example.com” _user = “示例” ## 静态 URL 映射 ## _cdnbase = "http://static.example.org/images" _dest="/var/www/images/" _cdnurls="" _isuploaded=0 _files="$@" ## rsync args ## _args="-aPv --ignore-existing" ## fail safe ## [[ "$_files" == "" ]] && { echo "Usage: $0 filexfcolrxrvkjutidsbhbcqexuvunyawhv.png filejgwsanhgqivghcfhomxmruykhukcwiwr.png"; exit 0; } ## Let us start uploading files. Bash for loop allows us to do a few more additional things, ## but I am keeping it simple here for demo purpose for i in $_files do # make sure $i file exist # if [ -f "$i" ] then rsync "$_args" "$i" ${_user}@${_server}:${_dest} _cdnurls="${_cdnurls}n${_cdnbase}/${i##*/}" _isuploaded=1 else echo "Error $i file not found." fi done if [ $_isuploaded -eq 1 ] then echo "CDN urls:" echo -e "$_cdnurls" echo fi
You can use the script as follows:
./script foo.png ./script foo.png bar.png ./script *.mov ./script test.gif
Sample outputs:
sending incremental file list test-image.gif 950 100% 0.00kB/s 0:00:00 (xfer#1, to-check=0/1) sent 1053 bytes received 31 bytes 197.09 bytes/sec total size is 950 speedup is 0.88 CDN urls: http://static.example.org/images/test-image.gif
Run it again:
./script test.gif
Sample outputs:
sending incremental file list sent 60 bytes received 12 bytes 13.09 bytes/sec 总大小为950 加速率为13.19 CDN 网址: http://static.example.org/images/test-image.gif
也可以看看
- Linux / Unix rsync:传输后删除源文件
如果有人知道此常见问题解答的更好解决方案,请在下面的评论中分享。