如何使用bash脚本解压目录中的每种tar文件?

时间:2019-04-09 01:03:06

标签: bash if-statement tar

我是为自动化任务编写bash脚本的初学者,我正尝试将一个目录中的所有tar文件解压缩(手动执行的方法太多),以获取一堆源代码文件。它们都是* .tar.gz,*。tar.xz或* .tar.bz2类型。

这是针对我正在做的Scratch LFS安装的Linux(我是第一个计时器),我不知道除了使用bash脚本以外,还有什么其他方法可以自动执行此任务。我的小脚本执行此操作的代码如下。

#!/bin/bash
for afile in 'ls -1'; do
    if [ 'afile | grep \"\.tar\.gz\"' ];
    then
        tar -xzf afile
    elif [ 'afile | grep \"\.tar\.xz\"' ]
    then
        tar -xJf afile
    elif [ 'afile | grep \"\.tar\.xz\"' ]
    then
        tar -xjf afile
    else
        echo "Something is wrong with the program"
    fi
done;

我希望它能解压目录中的所有内容并创建单独的目录,但是它退出并出现此错误:

tar (child): afile: Cannot open: No such file or directory
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2
tar: Error is not recoverable: exiting now

显然,它认为文件是实际文件,但我不知道如何将文件更改为正在通过我的for构造的每个文件。我将如何为此编写脚本,尤其是由于文件类型不同?

1 个答案:

答案 0 :(得分:2)

要使脚本以最少的更改运行,请在需要变量值时使用$afile。美元符号是可变参考;否则,您只会得到文字字符串'afile'。还要除去方括号,而应将变量echo grep移到for afile in `ls -1`; do if echo "$afile" | grep '\.tar\.gz' then tar -xzf "$afile" elif echo $afile | grep '\.tar\.xz' then tar -xJf "$afile" elif echo "$afile" | grep '\.tar\.bz2' then tar -xjf "$afile" else echo "Something is wrong with the program" fi done

*

由于您是bash初学者,因此让我们看一下可以编写脚本的其他各种方式。我会做一些改进。首先,you shouldn't loop over ls。通过遍历grep可以得到相同的结果。其次,[[是重量级工具。您可以使用==for afile in *; do if [[ "$afile" == *.tar.gz ]]; then tar -xzf "$afile" elif [[ "$afile" == *.tar.xz ]]; then tar -xJf "$afile" elif [[ "$afile" == *.tar.bz2 ]]; then tar -xjf "$afile" else echo "Something is wrong with the program" fi done 之类的内置shell结构进行一些简单的字符串比较。

case

实际上,使用>&2语句会更好。让我们尝试一下。另外,我们用for afile in *; do case "$afile" in *.tar.gz) tar -xzf "$afile";; *.tar.xz) tar -xJf "$afile";; *.tar.bz2) tar -xjf "$afile";; *) echo "Something is wrong with the program" >&2 esac done 将错误消息回显到stderr。总是一个好主意。

for afile in *.tar.{gz,xz,bz2}; do
    case "$afile" in
        *.tar.gz)  tar -xzf "$afile";;
        *.tar.xz)  tar -xJf "$afile";;
        *.tar.bz2) tar -xjf "$afile";;
    esac
done

如果我们只列出要循环的三种文件类型,我们甚至可以消除错误消息。那么就没有办法解决其他情况。

find

另一种完全不同的方法:使用-exec查找所有文件,并使用其{}操作为找到的每个文件调用命令。这里的find . -name '*.tar.gz' -exec tar -xzf {} \; find . -name '*.tar.xz' -exec tar -xJf {} \; find . -name '*.tar.bz2' -exec tar -xjf {} \; 是找到的文件的占位符。

<div class="container-div">

        <img src="https://cdn-image.travelandleisure.com/sites/default/files/styles/1600x1000/public/hotel-interior-room0416.jpg?itok=5gENxAK1" class="img-fluid rounded-top" style="width: 100%">
        <div class="price">229 $</div>
    </div>