shell——if语句

本文详细介绍了Shell脚本中if语句的使用,通过7个实战练习涵盖了判断用户权限、主机名合法性、网络连通性、进程存在性、用户存在性、软件包安装状态以及内核版本检查等场景,旨在提升Shell脚本控制流程的能力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值