shell_06--if判断语句

if语句:
 if条件语句的使用格式:
 1、单分支语句
    if 条件;then
       执行语句
    fi
 2、双分支语句
    if 条件;then
       执行语句1
    else
       执行语句2
    fi
 3、多分支语句
    if 条件;then
       执行语句1
    elif;then
       执行语句2
    elif;then
       执行语句3
    else
       执行语句4
    fi
 
退出码:
  exit
  在某些条件判断下,如果不满足该条件,我们必须手动退出程序,否则后面的代码无法执行;
  代码正确执行完成后,我们制定 exit 0 为正确退出码;
----------------------------------------------------------------------------
if语句实例:
1、判断某个文件是否存在
#!/bin/bash
	# 判断文件是否存在
	if [ $# -lt 1 ]; then
		echo "At least one argument." 
		exit 1 
	fi 

	if [ -e $1 ];then
		echo "这个文件存在"
	else
		echo "这个文件不存在"
	if

2、判断当前系统上是否有用户的默认shell程序是否为bash程序,如果有,就显示有多少个这类用户,否则就显示没有这类用户;【并且显示出那些用户是bash】

#!/bin/bash
	# 判断用户的默认shell程序类型
	
	declare -i sum=`grep "bin/bash$" /etc/passwd | wc -l`

	if grep "/bin/bash$" /etc/passwd &> /dev/null ; then
		echo "存在 $sum 个用户,shell程序为/bin/bash"
		grep "/bin/bash$" /etc/passwd | cut -d: -f1
		exit 0
	else
		echo "没有这类用户"
		exit 1
	fi

3、写出一个脚本程序,给定一个文件,比如:/etc/inittab a、判断这个文件中是否有空白行? b、如果有,则显示其空白行的行号,否则显示没有空白行

	#^[[:space:]]*$

	#!/bin/bash
	#
	
	B=`grep -n "^[[:space:]]*$" /etc/inittab | wc -l`
	C=`grep -n "^[[:space:]]*$" /root/abc | cut -d: -f1`
	
	if [ $B -eq 0 ] ; then
		echo "没有空白行"
		exit 1
	else
		echo  "有空白行,空白行为 $C 行"
		exit 0
	fi 

4、写一个脚本程序,给定一个用户,判断其UID与GID是否一样,如果一样,就显示该用户为“good guy”,否则显示为“bad guy”

	#!/bin/bash
	#
	
	1、for 做遍历 /etc/passwd
	for i in $(cat /etc/passwd);do   //sed可以完成;
		2、判断每一行的UID和GID
		if [ `cut -d: -f3 $i` = `cut -d: -f4 $i` ];then
			echo "good guy"
			exit 0
		else
			echo "bad guy"
			exit 1
		fi
	done

5、判断命令历史中历史命令的总条目是否大于1000,如果大于,则显示“some command will gone”,否则显示OK

#!/bin/bash
	#
	S=`history | awk '{print $1}' | tail -1`
	
	if [ $S -gt 1000 ];then
		echo "some command will gone"
		exit 0
	else
		echo "OK"
	fi

6、给定一个文件,如果是普通文件,就显示出来,如果是目录文件,也显示出来,否则就显示“无法识别”

#!/bin/bash
	#
	# input()
	read -t 5 -p ("请输入一个文件:") filename   // -t 等待时间
	echo 	# 默认用来换行

	if [ -n $filename ];then
		echo "eg. /etc/fstab"
		exit 8
	fi

	if [ -f $filename ]; then
		echo "$filename 是一个普通文件"
		exit 0
	elif [ -d $filename ];then
		echo "$filename 是一个目录文件"
		exit 0
	else
		echo "无法识别"
		exit 1
	fi

7、写一个脚本,能接受一个参数(文件路径),判断这个参数如果是一个存在的文件就显示“ok”,否则显示“No such file"

#!/bin/bash
	#
	
	read -p "请输入一个文件路径:" filename 
	
	if [ -e $filename ];then
		echo "OK"
	else
		echo "No such file"
	fi

8、写一个脚本,给脚本传递两个参数,显示两则之和和两者之积

#!/bin/bash
	#
	echo $[$1+$2]
	echo $[$1*$2]

  

  

  

  

 

猜你喜欢

转载自www.cnblogs.com/lzqitdl/p/11365095.html