目录
一、结构化命令
1. if条件语句
语法规则
1. 单条件判断
if ((condition));then
content
else
content
fi
2. 多条件判断
if [[ condition1 ]];then
content
elif [[ condition2 ]];then
content
else
content
fi
/bin/bash -n file.sh 用于检查脚本文件是否存在于法错误
逻辑运算符
运算符号 |
代表意义 |
= |
等于 应用于:整型或字符串比较 如果在[] 中,只能是字符串 |
!= |
不等于 应用于:整型或字符串比较 如果在[] 中,只能是字符串 |
< |
小于 应用于:整型比较 在[] 中,不能使用 表示字符串 |
> |
大于 应用于:整型比较 在[] 中,不能使用 表示字符串 |
-eq |
等于 应用于:整型比较 |
-ne |
不等于 应用于:整型比较 |
-lt |
小于 应用于:整型比较 |
-gt |
大于 应用于:整型比较 |
-le |
小于或等于 应用于:整型比较 |
-ge |
大于或等于 应用于:整型比较 |
-a |
双方都成立(and) 逻辑表达式 –a 逻辑表达式 |
-o |
单方成立(or) 逻辑表达式 –o 逻辑表达式 |
-z |
空字符串 |
-n |
非空字符串 |
-f |
常用!侦测『档案』是否存在 eg: if [ -f filename ] |
-d |
常用!侦测『目录』是否存在 eg: if [ -d dirname ] |
实用示例:自动备份mysql数据库脚本
`date +%Y%m%d` 表示系统时间
#!/bin/bash
#AUTO BACKUP MYSQL
#BY AUTHOR GCL 20191015
#1. define a directory to save the backup files.
backup_dir=/Users/guochunli/learning/shell/mysql_backup_files
#2. define the information about the database
user_name=root
database_schema=test
#3. indedicate back command
backup_cmd=/usr/local/opt/mysql@5.7/bin/mysqldump
#4. judge current user
if [ $UID -ne 0 ];then
echo "Operation not permitted!Must use root to do it!"
exit
fi
#5. check if the directory is existed
if [ ! -d ${backup_dir} ]; then
mkdir -p ${backup_dir}
echo "The directory is created successsfully!"
else
echo "The directory is existed! Please move on!"
fi
#6. execute backup command
${backup_cmd} -u${user_name} -p -P3306 -d ${database_schema} > ${backup_dir}/${