shell学习:第二阶段笔记汇总

本文详细介绍了Shell脚本的基础知识,包括if条件语句、for、while、until循环,case分支和select菜单。此外,还讲解了如何处理用户输入,以及脚本控制技巧,如处理信号、后台运行、预定时间执行和开机自启动等。
摘要由CSDN通过智能技术生成

目录

一、结构化命令

1. if条件语句

2. for循环语句

3. while循环语句

4. until循环语句

5. case分支语句

6. select循环语句

二、处理用户输入

三、脚本控制

1. 处理信号

2. 以后台模式运行脚本

3. 在非控制台下运行脚本

4. 作业控制

5. 预定时间运行

6. 开机自启动脚本


一、结构化命令

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}/${
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值