定义变量
fileName=text.txt
变量名称fileName,变量名称text.txt
使用变量
$fileName
用美元符号$开头,后面加变量名称,即可使用变量
使用用户输入参数
打印第一个参数
echo $1
函数结果转字符串
打印年月日时分秒
echo `date +%Y%m%d%H%M%S
IF条件控制语句
语法:
if condition
then
dosomething
elif condition
then
dosomething
else
dosomething
fi
或者,可以将then和if放在一行,但必须用分号;隔开
if condition ; then
dosometing
fi
判断文件是否存在
#!/bin/sh 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
fi #两个变量判断是否相等
if [ "$var1" = "$var2" ]; then
echo '$var1 eq $var2'
else
echo '$var1 not eq $var2'
fi
注意:if 后面一定要加空格
将linux命令输出结果转成字符串
用斜点单引号``包裹命令行
echo `stat -c %y test.sh | cut -c 1-10`
echo 打印换行符
echo -e "\n\n\n"