Linux使用tar和if else什么时候有文件

时间:2013-12-11 01:24:26

标签: linux bash tar

我有一个简单的问题。我希望这个脚本会说如果tar里面有一个文件“echo tar成功!”否则“echo没有任何文件”。

这是我的剧本:

stat -c"%z;%n" * | grep '^2013-12-04' |  awk -F';' '{ print $2 }' |  xargs tar -zcvf file.tar.gz
if[]??

3 个答案:

答案 0 :(得分:0)

试试这个

如果成功

回声$?将返回0

否则会返回非零值。

其他选项是tar -tvf,它将测试存档。基于tar -tvf的返回值。你可以查看你的文件列表。但如果它是一个巨大的文件,你可能需要使用head -n检查前几个文件。

这是一个很好的参考 http://unixhelp.ed.ac.uk/scrpt/scrpt2.2.2.html 〔实施例

你可以在你的bash脚本中添加这样的东西。 (只是对tar文件进行了硬编码)

tar -xvf test.tar>的/ dev / null的

如果[“$?” -eq 0]

然后

回声“成功”

否则

回音“错误”

网络连接

希望这有帮助

Tharanga Abeyseela

答案 1 :(得分:0)

function test_tar {
   if [[ $(tar -ztvf $1 | wc -l) != 0 ]]; then echo 'tar successful!'; else echo "don't have any files"; fi
}

$ test_tar non_empty_tar
tar successful!
$ test_tar empty_tar
don't have any files

答案 2 :(得分:0)

我认为你的剧本有问题。

stat -c "%z;%n" * | grep '^2013-12-04' | awk -F';' '{print $2}' | xargs tar -zcvf file.tar.gz 
if [[ $(zcat file.tar.gz | tar -tf - | wc -l) != 0 ]]; then 
    echo 'tar successful!'
else 
    echo "don't have any files"
fi