Shell编程总结

目录

[0.关于 ( ),\` \`,{ },\[ \],(( )), ,(( )),\[ ]](#0.关于 ( ),` `,{ },[ ],(( )),[ ],(( )),[[ ]])

[1.if 判断](#1.if 判断)

[2.case 语句](#2.case 语句)

[3.for 循环](#3.for 循环)

[4.while 循环](#4.while 循环)

5.函数

[6.应用:监测 MySQL 数据库异常](#6.应用:监测 MySQL 数据库异常)


0.关于 ( ),\` \`,{ },\[ \],(( )), ,(( )),\[ ]

  1. $( ) 与 ` ` (反引号) 都是用做命令替换
  2. **{ }** 用于**变量替换**。一般情况下,var 与{var} 并没有不一样。但是用 { } 会比较精确的界定变量名称的范围。
  3. \[ \] (( )) 是一样的,都是进行数学运算。支持+ - * / %:分别为 "加、减、乘、除、取模"。但是bash只能作整数运算,浮点数当作字符串处理。
  4. 即为test命令的另一种形式。
  5. **(( )) \[ ]**分别是 的针对数学比较表达式和字符串表达式的加强版。其中(( )),不需要再将表达式里面的大小于符号转义。

1.if 判断

bash 复制代码
#基本语法
if [ 条件判断式 ]
then
程序
elif [ 条件判断式 ]
then
程序
else
程序
fi
bash 复制代码
#!/bin/bash
read -p "input two number": a b
if [ $a -lt $b ]; then
 echo "$a < $b"
elif [ $a -eq $b ]; then
 echo "$a = $b"
else
 echo "$a > $b"
fi

2.case 语句

bash 复制代码
#基本语法
case $变量名 in
"值 1")
如果变量的值等于值 1,则执行程序 1
;;
"值 2")
如果变量的值等于值 2,则执行程序 2
;;
...省略其他分支...
*)
如果变量的值都不是以上的值,则执行此程序
;;
esac
注意
bash 复制代码
#!/bin/bash
case $1 in
"1")
    echo "aaa"
;;       #相当于break
"2")
    echo "bbb"
;;
*)
    echo "ccc"
;;
esac

3.for 循环

bash 复制代码
#基本语法
for (( 初始值;循环控制条件;变量变化 ))
do
程序
done

for 变量 in 值 1 值 2 值 3...
do
程序
done
bash 复制代码
#!/bin/bash
sum=0
for((i=0;i<=100;i++))
do
sum=$[$sum+$i]
done
echo $sum

#!/bin/bash
for i in aaa bbb ccc
do
echo $i
done

4.while 循环

bash 复制代码
#基本语法
while [ 条件判断式 ]
do
程序
done
bash 复制代码
#!/bin/bash
sum=0
i=1
while [ $i -le 100 ]
do
sum=$[$sum+$i]
i=$[$i+1]
done
echo $sum

5.函数

bash 复制代码
#基本语法
[ function ] funname[()]
{
Action;
[return int;]
}
bash 复制代码
#!/bin/bash
function sum()
{
s=0
s=$[$1+$2]
echo "$s"
}

read -p "Please input the number1: " n1;
read -p "Please input the number2: " n2;
sum $n1 $n2;

6.应用:监测 MySQL 数据库异常

bash 复制代码
#安装mysql: 
yum install mysql-server -y  #CentOS
systemctl start mysqld

sudo apt-get install mysql-server  #Ubuntu
systemctl start mysql
bash 复制代码
#!/bin/bash
#or $(netstat -lntup|grep 3306|wc -l)
if [ `netstat -lntup|grep 3306|wc -l` -gt 0 ]; then
 echo "MySQL is Running"
else
 echo "MySQL is Stopped"
 systemctl start mysqld
fi
相关推荐
A小辣椒3 小时前
TShark:Wireshark CLI 功能
linux
A小辣椒7 小时前
TShark:基础知识
linux
AlfredZhao9 小时前
OCI 明明分配了 200G 系统盘,为什么 df 只看到 30G?
linux·oci
AlfredZhao1 天前
vi 删除指定范围的行,不用再反复按 dd
linux·vi
用户9718356334661 天前
银河麒麟 KY10 申威(SW64) 安装 nginx-1.16.1-2.p01.ky10.sw_64.rpm 详细步骤
linux
猪脚踏浪1 天前
linux 拷贝文件或目录到指定的位置
linux
摇滚侠2 天前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
bush42 天前
嵌入式linux学习记录十四、术语
linux·嵌入式
载数而行5202 天前
Linux 11 动态监控指令top
linux
不会C语言的男孩2 天前
Linux 系统编程 · 第 8 章:进程基础
linux·c语言