1)例如:挂载光盘的操作,先判断挂载点目录是否存在,若不存在则新建此目录
Vi chkmountdir.sh,内容如下:
vim chkmountdir.sh
#!/bin/bash
mount_dir="/media/cdrom"
if [ ! -d $mount_dir ]
then
mkdir -p $mount_dir
fi
2)判断当前用户是不是root,如果不是则报错并执行exit 1退出脚本(1表示退出后的返回状态值),而不再执行其他代码
[root@localhost ~]# vim chkifroot.sh
#!/bin/bash
if [ "$USER" != "root" ]
then
echo "cuowu:fei root yonghu,quanxian buzu"
exit 1
fi
fdisk -l /dev/sda
执行脚本:./chkifroot.sh,因为当前登录的用户是root,所以执行fi之后的代码
[root@localhost ~]# chmod +x chkifroot.sh
[root@localhost ~]# ./chkifroot.sh
Disk /dev/sda: 107.4 GB, 107374182400 bytes
255 heads, 63 sectors/track, 13054 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector>
I/O>
Disk>
Device Boot Start End Blocks > /dev/sda1 * 1 64 512000 83 Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2 64 13055 104344576 8e Linux LVM
2、双分支if语句应用,语句结构如图:
对于双分支的选择结构,要针对“条件成立“,”条件不成立”,两种情况分别执行不同的操作
1)例如:编写一个连通性测试脚本pinghost.sh,
[root@localhost ~]# vim pinghost.sh
#!/bin/bash
ping -c 3 -i 0.2 -w 3 $1 &> /dev/null //检查目标主机是否能连通
if [ $? -eq 0 ] //判断前一条命令的返回状态
then
echo "host $1 is up."
else
echo "host $1 is down."
fi
[root@localhost ~]# chmod +x pinghost.sh
[root@localhost ~]# ./pinghost.sh 192.168.1.1
host 192.168.1.1 is up.
[root@localhost ~]# ./pinghost.sh 192.168.1.0
host 192.168.1.0 is down.
在上述脚本中,为了提高ping命令的测试效率,使用了“ -c . -i . -w,选项,分别指定只发送三个测试包,间隔0.2秒,超时3秒,另外,通过“&> /dev/null"屏蔽了ping命令执行过程的输出信息。
2)再例如:通过shell脚本检查vsftpd服务是否运行,如果已运行则列出其监听地址、pid号,否则输出提示“vsftpd服务不可用!”
首先安装vsftpd软件,开启vsftpd服务(软件统光盘里)