if流程控制语句
if 条件判断语句;then
command1
elif 条件判断语句;then
command2
else
command3
fi
练习1
根据当前登录用户uid判断是否为超级用户
提示:uid=0代表超级用户
如果是超级用户输出”the user is root”,否则输出”the user is not root”
#!/bin/bash
if [ “id -u” -ne 0 ]; then
echo “the user is not root”
else
echo “the user is root”
fi
练习2
用户输入云服务器相关信息(主机名),判断主机名输入是否合法
#!/bin/bash
read -p ‘请输入主机名:’ hostname
if [-z "${hostname}" ];then
ehco “please rewrite hostname”
else
echo $hostname
练习3
判断当前主机是否和远程主机ping通
#!/bin/bash
read -p "please input ipaddress:" address
#[ ping -c1 $address &>/dev/null ] && echo “disconnect” || ehco “connect”
#或
ip=$*
if [ -z ip ];then
echo 1
else
ping -c1 $ip &> /dev/null
if [ $? -eq 0];then
ehco “$ip can ping”
else
echo “ip can not ping”
fi
fi
练习4
判断Web服务器中httpd进程是否存在
#!/bin/bash
name = $*
gprep $name &> /dev/null
if [ $? -eq 0 ];then
echo “$name process exists”
else
echo “$name process not exists”
fi
练习5
输入一个用户,用脚本判断该用户是否存在?
#!/bin/bash
userid = $*
ip $userid &> /dev/null
if [ $? -eq 0 ];then
echo “$userid exists”
else
echo “$ userid not exists”
fi
练习6
判断一个软件包是否安装
如果没安装则安装它(假设本地yum源已配好)
#!/bin/bash
read -p "please input package name:" name
rpm -ql $name &> /dev/null
if [ $? -eq 0 ];then
echo "software has installed"
else
echo "software uninstall"
dnf install -y $name 1> /dev/null
if [ $? -eq 0];then
echo "$name install succeed"
else
echo "$name install failed"
fi
fi
练习7
判断当前内核主版本是否为2,且次版本是否大于等于6
如果都满足则输出当前内核版本,返回内核版本
uname -r 第一列主版本,第二列次版本
#!/bin/bash
versdetail='uname -r'
Mainversion='awk -F . ‘$1’ versdetail'
Salveversion='awk -F . ‘$2’ versdetail'
if [ $Mainversion == 2 -a $Salveversion -ge 6 ];then
echo “$versdetail”
fi