Shell编程指南

基础知识

shell执行方式   sh xx.sh (文件须有r权限)  ||  ./xx.sh (文件须有x权限) 注:sh xx.sh方式比较安全
文件名后缀 .sh
shell内容开头 #!/bin/bash || #!/bin/sh || #!/bin/csh || #!/bin/ksh 注:#!/bin/bash 使用比较多
退出  exit 0

变量赋值与使用

不需要定义即可直接使用  注:变量赋值时=号两端不能有空格
以$变量名或${变量名}访问变量内容

流程控制

判断  注:确保方括号的空格 ; 确定每个条件都有then

if [ –d ‘dirname' ];then 
    命令集1
elif 条件2;then
    命令集2
else
     命令集4
fi

case $变量 in 
match_1 )
        命令集1
        ;;
match_2)
        命令集2
        ;;
……
*)(可选)
        命令集n
        ;;
esac

循环

1.while 条件

do

        //TODO

done

2.until 条件

do 
    命令集
done

 
3.for ((初始值;条件;步进))

do 
    命令集
done

4.for 循环变量 in 变量列表

do 
    命令集
done

常用判断条件语句

判断文件类型

测试标志    语义    举例
-e    “文件或目录”是否存在    test –e $file_name
-f    “文件或目录”是否存在且为文件    test –f $file_name
-d    “文件或目录”是否存在且为目录    test –d “/boot”
-b    “文件或目录”存在且为块设备    test –b “/dev/sda1”
-c    “文件或目录”存在且为字设备    test –c “/dev/tty0”
-S    “文件或目录”存在且为Socket文件    test –S “/var/run/rpcbind.sock”
-p    “文件或目录”存在且为FIFO文件    test –p $file_name
-L    “文件或目录”存在且为链接文件    test –L $file_name

判断文件权限

测试标志    语义
-r    “文件或目录”是否存在且具有可读权限
-w    “文件或目录”是否存在且具有可写权限
-x    “文件或目录”是否存在且具有可执行权限
-u    “文件或目录”存在且具有SUID的属性
-g    “文件或目录”存在且具有SGID的属性
-k    “文件或目录”存在且具有Sticky bit的属性
-s    “文件或目录”存在且为非空文件

文件之间比较

测试标志    语义
-nt    “文件名1”是否比”文件名2”新 (newer than)
-ot    “文件名1”是否比”文件名2”旧(older than)
-ef    判断”文件名1”和”文件名2”是否为同一个文件,主要用来判断硬链接,即两个文件是否指向同一个inode节点

整数之间比较

测试标志    语义
-eq    两数相等(equal)
-ne    两数不等(not equal)
-gt    整数1大于整数2(greater than)
-lt    整数1小于整数2(less than)
-ge    整数1大于等于整数2(greater than or equal)
-le    整数1小于等于整数2(less than or equal)

与、或、非
测试标志    语义
-a    (and) 两个条件同时成立则返回true  test –e file1 –a –d file2
-o    (or)两个条件任意一个成立则返回true  test –r file1 –o –x file2
!    (非)当前条件取非  test ! –d file1

控制结构

计算整数变量值

expr  注: 运算符号和参数之间要有空格分开;通配符号(*),在作为乘法运算符时要用;
let 例子:let s=(2+3)*4