条件判断(if,case)和循环(for,until,while等)详解(附例题正解)

脚本中的if条件判断和循环

在linux下,写脚本是我们必不可少的。在写脚本的过程中,if判断和各种的循环是我们常用的。这里,详细的说一下条件判断以及循环的使用。

条件判断:if 和 else

1.if

shell程序中的条件分支是通过if条件语句来实现的,其格式一般为if -then -fi ,这样的是单分支语句,还有的一种就是if-then-else-fi两种。

(1)if-then语法格式:   #由于粘贴图片易乱格式,为方便观看,我直接附上正解源码,带结果

if 命令行

then 

命令行

fi 

(2)if-then-else-fi语法格式

if  CONDITION1; then

if-true

elif CONDITION2; then

if-ture

elif CONDITION3; then

if-ture

else

all-false

fi 

这个主要还是通过案例,多练习才能熟练的使用。下面我会做一些案例供参考。

2.case

if条件语句用于在两个选项中选定一项,而case条件选择为用户提供了根据字符串或变量的值从多个选项中选择一项的方法,其格式为:

case string in

pat1)

command1

;;

pat2)

command2

;;

……

*)

other command

esac

其中case支持使用shell的通配符("*","?","[]"),通常用*作为case命令的最后运算式以便在前面找不到相应的匹配项时执行“其他命令行”的命令。

1、写一个脚本/root/bin/createuser.sh,实现如下功能:

使用一个用户名做为参数,如果指定参数的用户存在,就显

示其存在,否则添加之;显示添加的用户的id号等信息

[root@localhost 0812]# ls /home

alice  bash  basher  gentoo  gentoo1  kk  nologin  test1  testbash  tom

[root@localhost 0812]# bash iftest1.sh 

Please input one username:kk

The user is exist

uid=1000(kk) gid=1000(kk) groups=1000(kk),10(wheel)

[root@localhost 0812]# bash iftest1.sh 

Please input one username:zz

Add zz finished

uid=2018(zz) gid=2018(zz) groups=2018(zz)

[root@localhost 0812]# ls /home

alice  bash  basher  gentoo  gentoo1  kk  nologin  test1  testbash  tom  zz

[root@localhost 0812]# cat iftest1.sh 

#!/bin/bash

#

read -p "Please input one username:" username

if  grep ^$username.* /etc/passwd &> /dev/null ;then

echo "The user is exist"

echo "`id $username`"

else

useradd $username

echo "Add $username finished"

echo "`id $username`"

fi

[root@localhost 0812]# 

2、写一个脚本/root/bin/yesorno.sh,提示用户输入yes或

no,并判断用户输入的是yes还是no,或是其它信息

read -p "please enter [yes] or [no]:" so

case $so in

[Yy]|[Yy][Ee][Ss])

echo your choice is yes! ;;

[Nn]|[Nn][Oo])

echo your choice is no! ;;

*)

echo unknown ;;

esac

3、写一个脚本/root/bin/filetype.sh,判断用户输入文件路

径,显示其文件类型(普通,目录,链接,其它文件类型)

#参考下面的/var/下文件的判断

4、写一个脚本/root/bin/checkint.sh,判断用户输入的参数

是否为正整

[root@localhost 0812]# vi 判断参数.sh

[root@localhost 0812]# bash 判断参数.sh 

Please input one number:

At least input one number 

[root@localhost 0812]# bash 判断参数.sh 

Please input one number:ee

“error”

[root@localhost 0812]# bash 判断参数.sh 

Please input one number:55

The num type is int

[root@localhost 0812]# cat 判断参数.sh 

#!/bin/bash

#

read -p 'Please input one number:' num

if [ -z $num ];then

echo "At least input one number "

exit 1

fi

if [[ $num =~ ^[1-9]{1,} ]];then

echo "The num type is int"

else

echo “error”

fi

[root@localhost 0812]# 

3.for

for 变量名 in 列表;do

循环体

done

 

依次将列表中的元素赋值给“变量名”; 每次赋值后即执行一次循环体; 直到列表中的元素耗尽,循环结束

列表生成方式:

(1) 直接给出列表

(2) 整数列表:

(a) {start..end}

(b) $(seq [start [step]] end)

(3) 返回列表的命令

$(COMMAND)

(4) 使用glob,如:*.sh

(5) 变量引用;$@, $*

1、判断/var/目录下所有文件的类型

[root@localhost d0816]# vi 查看文件类型2.sh

[root@localhost d0816]# bash 查看文件类型2.sh 

The account type is :d

The adm type is :d

The cache type is :d

The crash type is :d

The db type is :d

The empty type is :d

The games type is :d

The gopher type is :d

The kerberos type is :d

The l2a type is :f

The lib type is :d

The local type is :d

The lock type is :d

The log type is :d

The mail type is :d

The nis type is :d

The opt type is :d

The preserve type is :d

The run type is :d

The spool type is :d

The tmp type is :d

The yp type is :d

[root@localhost d0816]# ls /var

account  cache  db     games   kerberos  lib    lock  mail  opt       run    tmp

adm      crash  empty  gopher  l2a       local  log   nis   preserve  spool  yp

[root@localhost d0816]# cat 查看文件类型2.sh 

#!/bin/bash

#

for name in `ls /var/.`

do

if [ -f /var/$name ];then

echo "The $name type is :f"

elif [ -d /var/$name ];then

echo "The $name type is :d"

elif [  -h /var/$name ];then

echo "The $name type is :link"

else

echo "The $name type is :other"

fi

done

2、添加10个用户user1-user10,密码同用户名

[root@localhost bin]# cat adduser.sh 

#!/bin/bash

#

for num in `seq 1 10`;do

if id user$num&>/dev/null;then

echo "user$num exist!";continue

else

useradd user$num&&echo "user$num"|passwd –stdin user$num

fi

done

 3、/etc/rc.d/rc3.d目录下分别有多个以K开头和以S开头的

文件;分别读取每个文件,以K开头的文件输出为文件加stop

,以S开头的文件输出为文件名加start;

“K34filename stop”

“S66filename start”

[root@localhost d0816]# vi KS.sh

[root@localhost d0816]# bash KS.sh

K50netconsole stop

S10network start

[root@localhost d0816]# cat KS.sh

#!/bin/bash

#

for name in `ls /etc/rc.d/rc3.d`

do

if [[ $name =~ ^K.* ]];then

echo "$name stop"

fi

if [[ $name =~ ^S.* ]];then

echo "$name start"

fi

done

 4、写一个脚本,提示输入正整数n的值,计算1+2+3+…n的

总和

[root@localhost d0816]# bash 1-n和.sh 

Please input int number:5

The 1-5的和为:15

[root@localhost d0816]# bash 1-n和.sh 

Please input int number:3

The 1-3的和为:6

[root@localhost d0816]# cat ./1

100sum.sh  1-n和.sh   

[root@localhost d0816]# cat ./1-n和.sh 

#!/bin/bash

#

read -p 'Please input int number:' num

if [ $num -lt 1 ];then

echo "Aleast input one number"

exit 1

fi

sum=0

for n in $(seq 1 $num)

do

let sum=$sum+$n

done

echo "The 1-$n的和为:$sum"

 

 5、写一个脚本,提示请输入网络地址,如192.168.0.0,判

断输入的网段中主机在线状态

[root@localhost bin]# cat updown.sh 

#!/bin/bash

#

read -p "please enter a ip address:" ipaddr

ip=`echo "$ipaddr"|egrep -o "^[[:digit:]]{1,3}\.[[:digit:]]{1,3}."`

#echo "$ip"

echo

nu=0

nd=0

#for i in `seq 0 254`;do

for j in `seq 1 255`;do

if ping -W1 -c1 ${ip}252.${j} &>/dev/null ;then

let nu++

echo -e "\n\t\t${ip}252.${j}  is up  $nu"

else

let nd++

echo -e "\b\r$nd down"

fi

done

#done

4.while

while CONDITION; do

循环体

done

 CONDITION:循环控制条件;进入循环之前,先做一次判断;每一次循环之后会再次做判断;条件为“true”,则执行

一次循环;直到条件测试状态为“false”终止循环.

5.until 

 until CONDITION; do

循环体

 done

 进入条件: CONDITION 为false

 退出条件: CONDITION 为true

1、求100以内所有正整数之和

[root@localhost bin]# cat sum100.sh 

#!/bin/bash

#

i=1

while [ $i -le 100 ];do

let s=s+i

let i++

done

echo "$s"

2、通过ping命令探测172.16.250.1-254范围内的所有主机

的在线状态,统计在线主机和离线主机各多少。

[root@localhost until]# cat ping10.sh 

#!/bin/bash

#

i=1

NumUp=0

NumDown=0

echo

until [ $i -gt 254 ];do

if ping -W1 -c1 10.1.252.$i &>/dev/null ;then

let NumUp++

echo -e "\n\t\t 10.1.252.$i  is up  $NumUp"

    else

        let NumDown++

echo -e "\b\r$NumDown down"

    fi

let i++

done

 3、打印九九乘法表

#!/bin/bash

#

i=1

j=1

while [ $i -le 9 ]

do

for j in `seq 1 $i`

do

echo -ne "$j*$i=$[i*j]\t"

done

let i++

echo

done

4、利用变量RANDOM生成10个随机数字,输出这个10数字

,并显示其中的最大者和最小者

[root@localhost bin]# vi random.sh 

[root@localhost bin]# bash random.sh 

19182

The max number is 29660,The min number is 1200

[root@localhost bin]# cat random.sh

#!/bin/bash

#

i=1

random=$RANDOM

max=$random

min=$random

echo "$random"

while [ $i -le 10 ]

do

random=$RANDOM

if [[ $random -ge $max ]];then

max=$random

fi

if [[ $random -le $min ]];then

min=$random

fi

let i++

done

echo "The max number is $max,The min number is $min"

 5、打印国际象棋棋盘

root@localhost bin]# cat chess.sh 

#!/bin/bash

#

line=1

i=8

while [ $line -le 8 ] ;do

j=$line

while [ $j -le $i ] ;do

co=$[$j%2]

if [ $co -eq 1 ];then

echo -ne "\033[47m  \033[0m"

else

echo -ne "\033[40m  \033[0m"

fi

let j++

done

echo

let line++

let i++

done

原创文章,作者:zhong,如若转载,请注明出处:http://www.178linux.com/37090

(0)
zhongzhong
上一篇 2016-08-18
下一篇 2016-08-18

相关推荐

  • shell编程作业

    1、编写脚本/root/bin/systeminfo.sh,显示当前主机系统信息,包括主机名,IPv4地址,操作系统版本,内核版本,CPU型号,内存大小,硬盘大小。 [root@localhost sh.log]# cat systeminfo.sh  #!/bin/bash #author:DYW #显示当前主机系统…

    Linux干货 2016-08-15
  • 排错

    把/etc/inittab  模式改为6模式 怎么修复 1 先把 vim /etc/inittab 打开 2 把/etc/inittab 模式改为6 3 reboot 4 在倒计时完之前按任意键 5按A进入 6 在quiet  命令后面写入 3  模式 重启 7把 vim /etc/inittab 打开 8 把/etc…

    Linux干货 2017-05-15
  • Linux进程管理

    一、程序与进程           1、程序         程序是为了达到特定的目的,可以被计算机运行并且由命令代码组成的语句序列。       &…

    Linux干货 2015-05-14
  • haproxy 动静分离负载均衡、​stats页面实现​。

    实验环境:一台主机提供haproxy、nfs、mariadb,后端2台apache部署wordpress。 实验目的:haproxy使得动静分离、以及开启stats页面。 haproxy简单介绍 负载均衡的解决方案,支持4、7层,特点是单进程模型(可配置为多进程模型)单进程能支持非常大的并发链接数量(相比较其他软件)。 到今天,马哥课程中的负载均衡方案(lv…

    Linux干货 2017-02-18
  • 马哥教育网络班21期+第9周课程练习

    1、写一个脚本,判断当前系统上所有用户的shell是否为可登陆shell(即用户的shell不是/sbin/nologin);分别这两类用户的个数;通过字符串比较来实现; #!/bin/bash while read line; do     if [[ $line&n…

    Linux干货 2016-09-01
  • 初识 vi/vim文本编辑器

    我们操作文件,终究离不开编辑文件,对文件内容的编辑,Linux系统下,我们通常使用VI/VIM来编辑文件。VI是每个Linux都会自带的文本编辑器,VIM是VI的增强版,现在的最新版都已自带,但是可能有些发行版本没有自带,可以使用sudo apt-get install vim命令安装vim。 可以使用vi或者vim命令直接进入新的文本文件,或者vim 文件…

    Linux干货 2017-07-29