鸟哥基础第十三章

shell脚本对于系统管理非常重要,不会写也至少要能读懂

脚本开头有个特殊的注释:#!  这个是标注脚本所要用的解释器。

如#!/bin/bash    #!一定要合用。

test、[ ]

test的参数非常重要,不然就看不懂脚本
0表示成立,非0表示不成立
类型检测

-e:文件名是否存在,exist
-f:是否为文件,file
-d:目录
-b、-c、-s、-p、-L

权限

-r、-w、-x
-u、-g、-k  suid 、sgid、sbit (就是特殊权限)
-s:是否为空白文件

比较

-nt:newer than
-ot:older than
-et:equal than

数值判断

-eq: equal
-ne: not equal
-gt:  greater than
-lt:   less than
-ge: greater than or equal
-le:  less than or equal

字符串判断

-z:是否为空字符串
-n:是否为非空字符串
=
!=

多条件判断

-a:and 2个或多个条件一起满足
-o:or    满足一个即可

shell脚本的默认变量和函数的默认变量

shell

   sh shell.sh                opt1     opt2     opt3
           $0                       $1       $2         $3

function

function printit(){…}
printit    1
  $0       $1

shell的$1是脚本后面跟的参数,而函数的$1是函数后面的参数,两者不一致

判断、循环语句,[]主要用在if里面

if […]; then

elif […];then

….

else

….

fi
-—————————————————–

case $ in

“”)

……

;;

“”)

……
;;

*)

…..
;;

esac
-——————————————————-
while […]  成立的话一直运行。
do

…..

done
-——————————————————-
until [….] 成立的话就不再执行
do

…..

done
-——————————————————-
for ((   ..;   ..;   …   )) 两个括号是因为shell里面的数值运算多是先定义才能用的,不定义的话就要用(())括起来
do                             #for的的条件是清楚的,而while是不清楚的

………..

done
-———————————–
for var in  .. .. ..
do

……..

done

脚本调试

sh -x sh15.sh 可以针对脚本一步一步执行,便于找出问题所在

sh -n sh15.sh  检查语法错误,没错误的话不会显示任何东西