单分支if
if [] ;then
...
fi
或者
if []
then
...
fi
例子:
判断当前用户是否为root用户:
#!/bin/bash
test=$(env | grep "USER=" | cut -d "=" -f 2)
if [ "$test" == root ];then
echo "is root"
fi
判断根分区是否大于90%
root@jimo:/home/workspace/shell# df -h
文件系统 容量 已用 可用 已用% 挂载点
udev 3.8G 0 3.8G 0% /dev
tmpfs 770M 9.7M 760M 2% /run
/dev/sda1 211G 84G 117G 42% /
tmpfs 3.8G 140M 3.7G 4% /dev/shm
tmpfs 5.0M 0 5.0M 0% /run/lock
tmpfs 3.8G 0 3.8G 0% /sys/fs/cgroup
tmpfs 770M 20K 770M 1% /run/user/133
tmpfs 770M 40K 770M 1% /run/user/0
root@jimo:/home/workspace/shell# df -h | grep sda1 | awk '{print $5}' | cut -d "%" -f 1
42
脚本:
#!/bin/bash
test=$(df -h | grep sda1 | awk '{print $5}' | cut -d "%" -f 1)
if [ "$test" -ge 90 ]
then
echo "disk is full"
fi
双分支if
if []
then
....
else
...
fi
判断输入是否是目录
#!/bin/bash
#读取输入到dir变量
read -t 30 -p "input the dir name:" dir
if [ -d "$dir" ]
then
echo "is dir"
else
echo "not a dir"
fi
运行:
root@jimo:/home/workspace/shell# ./isdir.sh
input the dir name:dir
is dir
root@jimo:/home/workspace/shell# ls -l
总用量 24
-rw-r--r-- 1 root root 4359 2月 5 22:15 asdfghj
drwxr-xr-x 2 root root 4096 2月 6 15:57 dir
-rwxr-xr-x 1 root root 124 2月 12 09:22 isdir.sh
-rwxr-xr-x 1 root root 132 2月 11 16:09 isfull.sh
-rwxr-xr-x 1 root root 109 2月 11 14:30 isroot.sh
-rw-r--r-- 1 root root 0 2月 6 15:58 z
root@jimo:/home/workspace/shell#
判断apache服务是否启动
test=$(ps aux grep httpd grep -v grep)
#定义变量test 并且查找是否启动apache的结果赋值给test
#ps aux 查看当前所有正在运行的进程
#grep httpd 过滤出apache进程
#grep -v grep 去掉包含grep的进程 -v 取反
if [ -n "$test" ]
#判断test是否为空
then
#如果不为空则执行这段程序 把结果写入/tmp/autostart-acc.log 中
echo " $(date) httpd is ok " >> /tmp/autostart-acc.log
else
#如果为空这执行这段程序
#首先启动httpd服务
/etc/rc.d/init.d/httpd start &>/dev/null
#然后把事件记录在错误日志中
echo " $(date) httpd is no \n httpd is autostart now" >> /tmp/autostart-err.log
fi
(注意!!!!!!)
注意不要把文件名设置成有httpd的,命令执行ps进程搜索会搜索到自身,从而导致脚本失效
多分枝if
简易计算器
#!/bin/bash
read -t 30 -p "input a:" a
read -t 30 -p "input b:" b
read -t 30 -p "input op:" op
if [ -n "$a" -a -n "$b" -a -n "$op" ]
then
#判断是否是数字
t1=$(echo $a | sed 's/[0-9]//g')
t2=$(echo $b | sed 's/[0-9]//g')
if [ -z "$t1" -a -z "$t2" ]
then
if [ "$op" == "+" ]
then
sum=$(($a+$b))
elif [ "$op" == "-" ]
then
sum=$(($a-$b))
elif [ "$op" == "*" ]
then
sum=$(($a*$b))
elif [ "$op" == "/" ]
then
sum=$(($a/$b))
fi
echo "$a $op $b=$sum"
else
echo "not number"
fi
else
echo "not empty"
fi
运行结果:
root@jimo:/home/workspace/shell# ./cal.sh
input a:12
input b:23
input op:*
12 * 23=276
case
注意双分号
#!/bin/bash
read -t 30 -p "input 1,2 or 3:" cho
case "$cho" in
"1")
echo "input 1"
;;
"2")
echo "input 2"
;;
"3")
echo "input 3"
;;
*)
echo "input error"
esac
结果:
root@jimo:/home/workspace/shell# ./case.sh
input 1,2 or 3:1
input 1
root@jimo:/home/workspace/shell# ./case.sh
input 1,2 or 3:4
input error