---
title: "从一个日志脚本看Bash Shell语法"
author: "ginge"
date: "2009-01-06T15:32:54Z"
tags: []
categories: ["操作系统"]
slug: "bash-shell"
draft: false
lastmod: "2009-01-06T15:32:54Z"
id: 310979
url: "https://ginge.iteye.com/blog/310979"
---

**脚本的作用**

这个脚本的作用就是从一个文件里读取一个需要管理的所有log文件，并且读入一个数组。然后判断是否存在，如果不存在则忽略。如果存在将判断大小是否超过设定大小，如果超过则备份。

 

**脚本内容**

```
#!/bin/bash

##author:ginge

echo "logfiles to manage:"
logfiles=${1-./logfiles}
size=${2-100}

index=0;
#read the log file into the array
while read logfiles[$index]
  do
    echo "$index: ${logfiles[${index}]}"
    (( index +=1 ))
  done < $logfiles


i=0;
while [ $i -lt $index ]
  do
     logfile=${logfiles[$i]}

     (( i += 1 ))

     dir=${logfile%/*}
     if [ -z $logfile ] || [ ! -f $logfile ];then
       echo "$logfile doesn't exist. ignored."
       continue;
     fi

     echo "handling logfile: $logfile"
     echo "entering dir:$dir"
     cd $dir

     result="`find $logfile -size +${size}M`"
     if [ ! -z $result ]; then
       echo "backup $logfile..."
        cp $logfile $logfile".`date '+%G%m%d'`"
        : > $logfile
     else
        echo "it's not bigger than ${size} M"
     fi
     
  done
```

 

 

 

**Shell类型声明**

开头这里声明了使用bash

 

**注释**

SHELL的注释以#开头，可以从一行的任意位置开始

 

**命令参数读取**

注意到$1和$2没有？这代表第一和第二个命令参数。其它的有$0，$#和 $\*。$0代表当前shell，$#代表参数个数，$\*则代表所有参数

 

**变量声明**

脚本语言可以事先不变量，变量也是弱类型的，最近一次使用时是什么类型就是什么类型，变量区分大小写。

 

logfiles=${1-./logfiles}意思是如果存在第一个命令参数则使用它对logfiles赋值，如果不存在则赋值为./logfiles

 

 

**变量引用**

变量引用以$符号开始，严格点要使用${variable}形式

 

**循环**

支持for循环和while循环，也支持continue和break

 

**条件判断**

在shell里，通常使用test或者\[]来作条件判断，可以判断的类型很多，如大小，文件是否存在，是否目录等等。

 

 

**数组**

新版Bash支持一维数组。数组元素的声明是array\_name\[xx]。你可以只初始化一部分数组元素，也可以全部初始化。也就是说可以

Array\[0] =1

Array\[1] =1

Array\[2] =1

Array\[3] =1

Array\[10]=1

 

 

**文件读取**

使用一个&lt;符就行了

 

**变量计算**

这里我们使用了(())语法，当然也可以使用let语法。

 

**字符串操作**

%{logfile%/\*}表示最短截取，如果变量logfile当前的值为/vision/logs/app/app.log，那么截取后的值将是/vision/logs/app

 

 

 

**执行命令**

\`\` 这个\`是跟~同一个键的那个符号，假如这样一个语句

Result=\`date\`

执行后echo $Result将是这样的Tue Jan  6 15:13:41 CST 2009

 

 

**没有使用一些Shell命令有**

l  IO重定向

l  Here Document

l  管道

l  进程

l  命令执行结果

l  函数

l  嵌套shell

l  等等

 

需要详细了解上述命令读以下资料就已经足够了

 

**参考资料：**

l  Advanced Bash-Scripting Guide version 3.7.3

l  Shell十三问