bash 为每个目录创建一个 tar 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15936003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
for each dir create a tar file
提问by Amanada Smith
I have a bunch of directories that need to be restored, but they have to first be packaged into a .tar. Is there a script that would allow me to package all 100+ directories into their own tar so dir becomes dir.tar.
我有一堆目录需要恢复,但必须先将它们打包成 .tar。是否有脚本可以让我将所有 100 多个目录打包到它们自己的 tar 中,以便 dir 变为 dir.tar。
So far attempt:
到目前为止的尝试:
for i in *; do tar czf $i.tar $i; done
回答by hzrari
The script that you wrote will not work if you have some spaces in a directory name, because the name will be split, and also it will tar files if they exist on this level.
如果目录名称中有一些空格,则您编写的脚本将不起作用,因为名称将被拆分,并且如果它们存在于该级别,它也会解压缩文件。
You can use this command to list directories not recursively:
您可以使用此命令不递归地列出目录:
find . -maxdepth 1 -mindepth 1 -type d
and this one to perform a tar on each one:
而这个对每个人执行 tar :
find . -maxdepth 1 -mindepth 1 -type d -exec tar cvf {}.tar {} \;
回答by David W.
Do you have any directory names with spaces in them at that level? If not, your script will work just fine.
在该级别,您是否有任何带有空格的目录名称?如果没有,您的脚本将正常工作。
What I usually do is write a script with the command I want to execute echoed out:
我通常做的是写一个脚本,我想执行的命令回显出来:
$ for i in *
do
echo tar czf $i.tar $i
done
Then you can look at the output and see if it's doing what you want. After you've determined that the program will work, edit the command line and remove the echocommand.
然后你可以查看输出,看看它是否在做你想要的。在确定程序可以运行后,编辑命令行并删除echo命令。
回答by Aaron Kelly
If there are spaces in the directory names, then just put the variables inside double quotes:
如果目录名称中有空格,则只需将变量放在双引号内:
for i in *
do
tar czf "$i.tar" "$i"
done
回答by Mark Setchell
Get them all done simply and in parallel with GNU Parallel:
用GNU Parallel简单地并行完成它们:
parallel tar -cf {}.tar {} ::: *
If you want to check what it is going to do without actually doing anything, add --dry-runlike this:
如果您想在不实际执行任何操作的情况下检查它将要执行的操作,请添加--dry-run以下内容:
parallel --dry-run tar -cf {}.tar {} ::: *
Sample Output
样本输出
tar -cf ab.tar ab
tar -cf cd.tar cd
回答by Jalal Hajigholamali
if number of directories are very large and their names are too long
如果目录数量非常大且名称太长
after execution of statement number one
执行第一条语句后
for i in *
do
echo tar czf $i.tar $i
done
you will get error "string too long"
你会得到错误“字符串太长”

