shell 小结
程序员文章站
2022-06-29 13:29:21
...
文章目录
简例 demo
#!/bin/bash
cd /usr/local
ls
cd -
语法(syntax)
1. 自定义语法 (Custom syntax)
#!/bin/bash
var1=hello
var2=world
echo $var1 $var2
echo $USER `s home is $HOME
2. 系统语法 (system syntax)
#!/bin/bash
echo $HOME
echo $USER
3. 返回值语法(return value syntax)
#!/bin/bash
dt=`date`
dirs=`ls /usr/local`
echo $dt
echo $dirs
表达式(expression)
1. 命令表达式(command expression)
#!/bin/bash
if mkdir test
then
echo create dir success
else
echo failed
fi
2. 数学表达式(math expression)
[ $var1 -gt/-lt/-eq/-ge/-le/-ne $var2 ]
-gt >
-lt <
-ge >=
-le <=
-eq =
-ne !=
#!/bin/bash
var1=2
var2=3
var3=$[ $var1 + $var2 ]
if [ $var1 -gt $var3 ]
then
echo $var1 is bigger then $var3
else
echo $var1 is smaller then $var3
fi
3. 字符串表达式(string expression)
判断字符串是否一致
[ string1 =/!= string2 ]
#!/bin/bash
var1=abc
var2=def
if [ $var1 = $var2]
then
echo $var1 is $var2
else
echo different
fi
4. 文件判断表达式(File judgement expression)
- [ -d/-f/-e/-r/-w/-x filename ] 文件判断对应属性如下:
-d is dir
-f is file
-e is exists
-r is readable
-w is writeable
-x is excuteable
- 文件判断 [ file1 -nt/ot file2 ]
判断file1比file2 新/旧
- -nt file1 is newer
- -ot file1 is older
if [-d ./test]
then
mkdir test
else
echo dir2 is not exists
fi
控制结构(control structure)
if
#!/bin/bash
if expression
then
echo 1
echo 2
else
echo 3
echo 4
fi
for
- bash style
#!/bin/bash
for $i in value1 value2 value3
do
echo $i
done
example:
#!/bin/bash
for i in A B C D
do
echo $i
done
- C language style
#!/bin/bash
for((variable=init_value;variable<=n;variable++)))
do
echo xxx
echo xxx
done
demo
#!/bin/bash
sum=0
for((i=1;i<=100;i++))
do
sum=$[ $sum + $i ]
done
echo $sum
case
#!/bin/bash
case variable in
value1 1)
echo 1
;;
value2 2)
echo 2
;;
*)
echo 1
echo 2
;;
demo
#!/bin/bash
case $USER in
root)
echo "you are super master" $USER;;
json)
echo -n "you are " $USER;;
*)
echo sorry!
esac
导出数据库案例
导出现有数据库并删掉7天以前的数据库.
#!/bin/bash
filename=`date +%y%m%d`.tar.gz
if [ -f $filename ]
then
echo "file is exists!"
else
mysqldump -uroot -proot yii2basic > /root/test/yii2basic.sql
tar -zcvf yii2basic.tar.gz yii2basic.sql
mv yii2basic.tar.gz $filename
rm -fr yii2basic.sql
echo "mysqldump done!"
fi
old = `date -d '-7 day' + %y%m%d`
if [ -f $old.tar.gz]
then
rm -fr ./$old.tar.gz
fi
上一篇: shell 小结