1、服务器上有一个目录/abc/123/images/,下面有按照每天日期的目录,如果day_20190109。
写一个脚本,把/abc/123/images/下面的2019年全年的目录打包压缩,如day_20190109压缩后为day_20190101.tar.gz,并删除掉day_20190109目录;
脚本内容如下:
[root@localhost_002 shell100]# cat 28.2.sh
#!/bin/bash
cd /root/image/
for d in `ls -d day_2018*`
do
tar -zcf $d.tar.gz $d && rm -fr $d
done
[root@localhost_002 image]# mkdir day_20180101
[root@localhost_002 image]# mkdir day_20181212
[root@localhost_002 image]# mkdir day_20180506
[root@localhost_002 image]# mkdir day_20180304
[root@localhost_002 image]# ls
day_20180101 day_20180304 day_20180506 day_20181212
[root@localhost_002 image]# cd -
/root/shell/shell100
[root@localhost_002 shell100]# sh 28.2.sh
[root@localhost_002 shell100]# cd -
/root/image
[root@localhost_002 image]# ls
day_20180101.tar.gz day_20180304.tar.gz day_20180506.tar.gz day_20181212.tar.gz
我们假设/root/image/有很多以天来命名的目录,需要对这个目录分别压缩,并删除源文件;
注释:首先用 cd 进入到这个目录下;
然后用 for d in `ls -d 2018*`;do tar zcf $d.tar.gz $d && rm -r $d
注意:在使用ls 的时候需要加上 -d 选项,表示打印当前目录,下一级目录不打印了;
如果不加 -d 脚本则有文件;如下对比;
#加 -d 如下:
[root@localhost_002 shell100]# cat 28.2.sh
#!/bin/bash
cd /root/image/
for d in `ls -d day_2018*`
do
echo $d
done
[root@localhost_002 shell100]# sh 28.2.sh
day_20180101
day_20180506
#不加 -d 则如下:
[root@localhost_002 shell100]# cat 28.2.sh
#!/bin/bash
cd /root/image/
for d in `ls day_2018*`
do
echo $d
done
[root@localhost_002 shell100]# sh 28.2.sh
day_20180101:
123
day_20180506:
123