xargs与tar合并查询文件并打包问题检查

今天在整理服务器上的日志的时候,希望能将日志打包保存之后再删除,然后就出现了问题了。

find /debugLog -mmin +21600 -type f -print | xargs tar cvf /debugLog_$(date +”%Y%m%d%H%M%S”).tar

会出现提示:

tar: Exiting with failure status due to previous errors

大意是上一步中存在错误,怎么查看错误是啥?

查一下,在《Linux常见问题解答–如何修复“tar:Exiting with failure status due to previous errors”》找到答案,只需要将v参数去掉就行。

使用下面的命令查看:

find /debugLog -mmin +21600 -type f -print | xargs tar cf /debugLog_$(date +”%Y%m%d%H%M%S”).tar

然后打印出好多的错误信息了:

tar: Removing leading `/’ from member names
tar: /debugLog/efast/20171204_b2c_apiv_apis_response_goods: Cannot stat: No such file or directory
tar: -: Cannot stat: No such file or directory
tar: get_all_list.txt: Cannot stat: No such file or directory
tar: /debugLog/wxauth/20180103_wxauth_115.239.174.134,: Cannot stat: No such file or directory
tar: 10.53.26.130.txt: Cannot stat: No such file or directory
tar: /debugLog/wxauth/20180103_wxauth_115.239.174.134,: Cannot stat: No such file or directory
tar: 10.53.29.194.txt: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors

对于第一行的错误,百度了一下,在《“tar: Removing leading `/’ from member names”的错误》找到答案,这个因为是相对路径的缘故,需要增加P参数。

命令改为:

# find /debugLog -mmin +21600 -type f -print | xargs tar cfP /debugLog_$(date +”%Y%m%d%H%M%S”).tar

然后,继续出现下面的错误了:

tar: /debugLog/efast/20171204_b2c_apiv_apis_response_goods: Cannot stat: No such file or directory
tar: -: Cannot stat: No such file or directory
tar: get_all_list.txt: Cannot stat: No such file or directory
tar: /debugLog/wxauth/20180103_wxauth_115.239.174.134,: Cannot stat: No such file or directory
tar: 10.53.26.130.txt: Cannot stat: No such file or directory
tar:/debugLog/wxauth/20180103_wxauth_115.239.174.134,: Cannot stat: No such file or directory
tar: 10.53.29.194.txt: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors

根据实际查看错误的文件名发现,这两个文件其实都有特殊:

/debugLog/efast/20171204_b2c_apiv_apis_response_goods – get_all_list.txt

/debugLog/wxauth/20180103_wxauth_115.239.174.134, 10.53.29.194.txt

因为xargs默认分割符是空格,所以,上面的就被分为5个文件了。

/debugLog/efast/20171204_b2c_apiv_apis_response_goods

get_all_list.txt

/debugLog/wxauth/20180103_wxauth_115.239.174.134,

10.53.29.194.txt

所以,我们需要将分割符换一下,代码改为下面形式就OK了~

find /debugLog -mmin +21600 -type f -print0 | xargs -0 tar cfP /debugLog_$(date +”%Y%m%d%H%M%S”).tar

完美解决,如果你需要压缩完毕后就直接删除文件,则需要增加参数

find /debugLog -mmin +21600 -type f -print0 | xargs -0 tar cfP /debugLog_$(date +”%Y%m%d%H%M%S”).tar –remove-files

就可以了。

介于上面的文件名问题,我比较不赞同直接增加参数,毕竟,架不住有时候文件名里面出现个/被解析为根目录呢?

使用下面命令麻烦了点,但是稍微比较保险,你说呢?

find /debugLog -mmin +21600 -type f -print -exec rm -rf {} \;

发表评论