1

问题:

我想解压一个 tarfile,它本身有许多 tar 文件,并删除所有 tar 文件中的文件,我希望所有这些进程在 Unix bash 脚本中并行运行。

条件:

  1. 如果任何解压缩/删除过程有任何错误,脚本应该返回一个错误。
  2. 只有在所有 N 个(解压缩和删除)进程成功完成后,它才应该返回成功。

建议的解决方案:

 mkdir a
 tar -C a -xvf b.tar
 cd a
 for i in *
 do
 rm -r $i &
 done
4

3 回答 3

3

如果你安装了 GNU Parallel http://www.gnu.org/software/parallel/你可以这样做:

tar xvf foo.tgz | perl -ne 'print $l;$l=$_;END{print $l}' | parallel rm

如果您没有空间来提取完整​​的 tar.gz 文件,这很有用,但您需要在解压缩文件时对其进行处理:

tar xvf foo.tgz | perl -ne 'print $l;$l=$_;END{print $l}' | parallel do_stuff {}\; rm {}

您可以通过以下方式安装 GNU Parallel:

wget http://git.savannah.gnu.org/cgit/parallel.git/plain/src/parallel
chmod 755 parallel
cp parallel sem

观看 GNU Parallel 的介绍视频以了解更多信息: https ://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

于 2012-05-09T21:59:17.663 回答
1
mkdir a
tar -C a -xvf b.tar
 cd a
 success=$(for i in *
 do
 rm -r $i || echo failed & # if a job fails false will be echoed
 done
 wait)
 # if any of the jobs failed, success will be set to a value other than ""
 [[ -z "$success" ]] && exit 0 || exit 1
于 2012-05-03T21:08:19.960 回答
1

答案tar xvf a.tar | tac | xargs -P 4 rm -rv的灵感来自Burton Samograd关于xargs -P

$ mkdir -p a/b/c/d
mkdir: created directory `a'
mkdir: created directory `a/b'
mkdir: created directory `a/b/c'
mkdir: created directory `a/b/c/d'

$ touch a/1 a/2 a/3 a/b/4 a/b/5

$ tar cf a.tar a

$ rm -rfv a
removed directory: `a/b/c/d'
removed directory: `a/b/c'
removed `a/b/4'
removed `a/b/5'
removed directory: `a/b'
removed `a/3'
removed `a/1'
removed `a/2'
removed directory: `a'

$ tar xvf a.tar | tac | xargs -P 4 rm -rv
removed `a/2'
removed `a/1'
removed `a/3'
removed `a/b/5'
removed `a/b/4'
removed directory: `a/b/c/d'
removed directory: `a/b/c'
removed directory: `a/b'
removed directory: `a'
于 2013-09-12T12:55:58.317 回答