Bash 脚本未按预期工作

Bash 脚本未按预期工作

所以,在编写脚本方面我完全是个新手,就像这是我的第一个脚本一样。我创建了以下脚本:

# This simply declares which states we are using to create tarballs from
for blah in ar ky ms ny; 
do 
    # This will go into each tomcat-state directory and create a tarball in /home/ec-user for all files older than 90 days
    find /var/www/apps/tomcat-${blah}/logs -type f -mtime +90 | xargs tar -cvzf /home/ec2-user/archive-${blah}.tar.gz; 

    # This creates a master archive tarball containing all the archive-state.tar.gz files
    tar -cvzf /home/ec2-user/ebd-log-archives.tar.gz /home/ec2-user/archive-${blah}.tar;

    # Since in step one, we archives all files older than 90 days, this step removes them.
    # find /var/www/apps/tomcat-${blah}/logs -type f  -mtime +90 -exec rm {} \;

    # And since we have the master archive file, this removes the archive-state files
    rm /home/ec2-user/archive-${blah}.tar.gz;
done

我已经注释掉了删除测试日志的操作。

问题是,当我获得主 tarball 时,它只包含 NY,或者我将其作为循环中的最后一个内容(我对此进行了测试以确保它不仅仅是一个奇怪的 NY 事情)

不确定发生了什么,我根据该服务器上措辞与此类似的旧脚本对其进行了测试,并且运行良好。

编辑:感谢您的回复,我已将脚本更新为:

# This creates the master tarball we will be using
tar -cvzf /home/ec2-user/ebd-log-archives.tar.gz

# This simply declares which states we are using to create tarballs from
for blah in ar ky ms ny; 
do 
    # This will go into each tomcat-state directory and create a tarball in /home/ec-user for all files older than 90 days
    find /var/www/apps/tomcat-${blah}/logs -type f -mtime +90 | xargs tar -cvzf /home/ec2-user/archive-${blah}.tar.gz; 

    # This creates a master archive tarball containing all the archive-state.tar.gz files
    tar -rvzf /home/ec2-user/ebd-log-archives.tar.gz /home/ec2-user/archive-${blah}.tar;

    # Since in step one, we archives all files older than 90 days, this step removes them.
    # find /var/www/apps/tomcat-${blah}/logs -type f  -mtime +90 -exec rm {} \;

    # And since we have the master archive file, this removes the archive-state files
    rm /home/ec2-user/archive-${blah}.tar.gz;
done

我将尝试运行此程序并发布更新

答案1

每次运行 时tar -c,该工具都会创建一个新档案。如果您告诉它使用现有名称(ebd-log-archives.tar.gz就您而言),旧档案将被覆盖。

你可以创建一个空的档案(“主档案”)位于循环之前,然后tar -r(而不是tar -c)位于循环内部。

man 1 tar

-c--create
创建一个新的档案。[…]

[…]

-r,--append
将文件附加到档案末尾。参数含义与-c( --create) 相同。

相关内容