Shell脚本
通俗地说,脚本是命令的集合。比如我们把如下命令放到一个文件里:
cd /work11/mywork;
ls;
mkdir aaa;
cd aaa;
那么这个文件就可以说是一个脚本。
shell脚本常用命令
命令 语法
if 条件执行 if 条件 then 指令
fi
case 分支执行 case 字符串变量 in
值1) 指令......
值2) 指令......
...
esac
while 条件为真时循环 do
指令......
done
until 条件为假时循环 until 条件
do
指令......
done
for 变量在表中时循环 for 变量名 in 字组表
do
指令......
done
test 条件测试,语法 test [选项] 参数 选项:
-f 文件存在
-gt greater than
-ge greater equal
-lt lower than
-le lower equal
shell脚本示例 (条件-if)
#!/usr/bin/ksh
If [ $# -ne 1 ]
then
echo “Usage:$0 filename”
exit
else
echo “ok”
fi
file=$1
awk –F”:” ‘{if( substr($2,1,2)==“vc”) printf(“rec=%s\n”,substr($0,index($0,”testPos”)) )}’ $file |head -1 |read val
if [ “X$val” == “X” ]
then
echo val is null!
elif [ $val –gt 3 ]
then
echo val greater than 3.
fi
Shell脚本示例(条件-case)
#!/usr/bin/ksh
param=$1
case $1 in
1)
echo “The param you input is 1”
;;
“xx”)
echo “xxxxxxxxx”
;;
“*”)
echo “The others…”
;;
esac
shell脚本示例(循环-while)
#!/usr/bin/ksh
echo “Continue?(y|n)”
read x
if [ “$x” = “y” –o “$x” = “Y” ]
then
echo “we’ll test the while,pls input”
read y
while [ “$y” != “n” ]
do
echo “Go on with the while”
echo “Input pls.”
read y
done
else
echo “exit”
exit
fi
shell脚本示例(循环-for)
#!/usr/bin/ksh
valList=“aa bb cc dd”
for currVal in ${valList}
do
case ${currVal } in
“aa”)
echo “currVal is aa”
;;
“*)
if echo $currVal |grep ^bb
then
echo “The value starts with bb!\n”
elif [ `echo $currVal|awk ‘{print substr($0,length($0),1)}’` = “d”
then
echo “The value is ended by d”
else
echo “Another values”
fi
;;
esac
done
#!/usr/bin/ksh
. ~/.profile >/dev/null
Shell脚本示例
BINPATH=/bill1/pkg1/bin
BINFILE=bill_backup#这不是unix命令,是我们自定义的程序
CFGPATH=/bill1/pkg1/config/static_backup
if ps -ef|grep -v grep |grep -q ${BINPATH}/${BINFILE}
then
echo ${BINPATH}/${BINFILE} is alive !
else
echo ${BINPATH}/${BINFILE} starts running ...
chmod u+x ${BINPATH}/${BINFILE}
nohup ${BINPATH}/${BINFILE} ${CFGPATH}/static_backup.cfg >/dev/null 2>&1 &
fi