概述
shell脚本是用C语言编写的程序,有变量也有流程控制语句,可直接执行不需要编译。常见的shell脚本解释器有bash、sh、csh等,一般放在文件系统根目录/bin目录下。可用任意文本编译器编写。
基本语法
第一行
#! 用来告诉系统它后面的参数是用来执行该脚本的程序。例如我们的shell脚本解释器是/bin/sh,那么脚本的第一句话为:#!/bin/sh
注释
#号开头语句表示注释,直到这一行结束。
使用变量
变量名=变量(注意:等号两边不能有空格)
取出变量名,可以在变量值前加一个美元符号($)。
例:
your_name="qinjx"
echo $your_name
花括号告诉shell我们要打印的变量your_name
echo “this is ${your_name}”
流程控制
if 的语法格式
if condition
then
command1
command2
fi
写成一行的语法:
if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo "true"; fi
应用实例
判断文件是否存在,shell脚本如下:
#!/bin/sh
# 判断文件是否存在
# link:www.jb51.net
# date:2013/2/28
myPath="/var/log/httpd/"
myFile="/var /log/httpd/access.log"
# 这里的-x 参数判断$myPath是否存在并且是否具有可执行权限
if [ ! -x "$myPath"]; then
mkdir "$myPath"
fi
# 这里的-d 参数判断$myPath是否存在
if [ ! -d "$myPath"]; then
mkdir "$myPath"
fi
# 这里的-f参数判断$myFile是否存在
if [ ! -f "$myFile" ]; then
touch "$myFile"
fi
# 其他参数还有-n,-n是判断一个变量是否是否有值
if [ ! -n "$myVar" ]; then
echo "$myVar is empty"
exit 0
fi
# 两个变量判断是否相等
if [ "$var1" = "$var2" ]; then
echo '$var1 eq $var2'
else
echo '$var1 not eq $var2'
fi
shell中使用符号“$?”来显示上一条命令执行的返回值,如果为0则代表执行成功。
tar -zcvf ../tar/app.tar.gz .
if [ $? = 0 ]; then
echo "make tar file ok"
else
echo "make tar file err"
fi