linux shell脚本判断某个文件的大小,符合条件则备份并重命名 linux系统中,写一个shell对指定目录下的文件大于特定...

linux shell\u811a\u672c\u5224\u65ad\u67d0\u4e2a\u6587\u4ef6\u7684\u5927\u5c0f\uff0c\u7b26\u5408\u6761\u4ef6\u5219\u5907\u4efd\u5e76\u91cd\u547d\u540d

cat test.sh
#!/bin/sh
file=$1
file_size=`du $file | awk '{print $2}'`
if [ $file_size -ge 10485760 ]
then
cp -p $file $file-bak
fi
chmod +x test.sh
./test.sh 1.txt
\u9010\u884c\u89e3\u91ca
1.
\u67e5\u770b\u811a\u672c\u6587\u4ef6test.sh
2.
\u5b9a\u4e49\u811a\u672c\u9ed8\u8ba4\u7528sh\u6267\u884c
3.
\u5c06\u6587\u4ef6\u8def\u5f84\u8d4b\u4e88file\u53d8\u91cf\u3002$1
\u8868\u793a\u4f4d\u7f6e\u53d8\u91cf\u5373\u4e0b\u9762\u76841.txt
4.
\u8ba1\u7b97\u6587\u4ef6\u5927\u5c0f\u5e76\u8d4b\u4e88file_size\u53d8\u91cf
5.
\u5982\u679c\u6587\u4ef6\u5927\u5c0f\u5927\u4e8e\u7b49\u4e8e10m.
10485760\u4e3a10m,-ge\u4e3a\u5927\u4e8e\u7b49\u4e8e\u3002
6.
if\u8bed\u6cd5\u5173\u952e\u5b57
7.
\u5c06\u6587\u4ef6\u91cd\u547d\u540d\u5907\u4efd
8.
if\u8bed\u6cd5\u5173\u952e\u5b57
9.
\u7a7a\u884c
10.
\u8d4b\u4e88\u811a\u672ctest.sh\u53ef\u6267\u884c\u6743\u9650
11.
\u6267\u884c\u811a\u672c\uff0c\u8f93\u5165\u4f4d\u7f6e\u53d8\u91cf1.txt.

\u7528perl\u5b9e\u73b0\u8f83\u5bb9\u6613

\u914d\u7f6e\u6587\u4ef6\uff1a /xxx/backup.conf
A 200
B 100
C 50

\u811a\u672c\uff1a /xxx/backup.pl
#!/usr/bin/perl
use strict;
use File::Basename;

# \u914d\u7f6e\u6587\u4ef6\u540d
my $config_file = "/xxx/backup.conf";
# \u6e90\u76ee\u5f55
my $src_dir = "/tmp";
#\u5907\u4efd\u76ee\u5f55
my $backup_dir = "/xxx/backup";
#\u5f53\u524d\u65e5\u671f
my $today = `date +%Y%m%d`;
$today =~ s/\n//;

# \u8bfb\u53d6\u914d\u7f6e\u6587\u4ef6

my %conf;
open CONFIG, "<", $config_file;
while() {
my($fname, $fsize) = split;
$conf{$fname} = $fsize * 1024 * 1024;
}
close(CONFIG);

# \u626b\u63cf\u6e90\u76ee\u5f55\uff0c\u9644\u5408\u6761\u4ef6\u5219\u8fdb\u884c\u5907\u4efd

my @files = ;
foreach my $file (@files) {
my $file_basename = basename($file);
if ( -f $file && $conf{$file_basename}) {
if( -s $file > $conf{$file_basename} ) {
system "cp ${file} ${backup_dir}/${file_basename}.${today}";
if($?) {
#\u9047\u5230\u9519\u8bef\u5c31\u9000\u51fa
die "copy ${file} to ${backup_dir}/${file_basename}.${today} failed!\n";
}
unlink ${file};
}
}
}

cat test.sh 
#!/bin/sh
FILE=$1
FILE_SIZE=`du $FILE | awk '{print $2}'`
if [ $FILE_SIZE -ge 10485760 ]
then
    cp -p $FILE $FILE-bak
fi

chmod +x test.sh 
./test.sh 1.txt

逐行解释

  1. 查看脚本文件test.sh

  2. 定义脚本默认用sh执行

  3. 将文件路径赋予FILE变量。$1 表示位置变量即下面的1.txt

  4. 计算文件大小并赋予FILE_SIZE变量

  5. 如果文件大小大于等于10M. 10485760为10M,-ge为大于等于。

  6. if语法关键字

  7. 将文件重命名备份

  8. if语法关键字

  9. 空行

  10. 赋予脚本test.sh可执行权限

  11. 执行脚本,输入位置变量1.txt.



扩展阅读:脚本编程教学 ... shell脚本基本常识 ... 100个必会的shell脚本 ... linux sed命令详解 ... shell脚本for循环 ... centos shell脚本 ... linux执行bash脚本 ... linux cat执行shell ... linux创建shell脚本并编辑 ...

本站交流只代表网友个人观点,与本站立场无关
欢迎反馈与建议,请联系电邮
2024© 车视网