条件判断(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)
上一篇 2016-08-18 10:09
下一篇 2016-08-18 10:09

相关推荐

  • 自制linux和内核编译

    自制linux和内核编译 1、分区并创建文件系统 fdisk /dev/sdb分两个必要的分区/dev/sdb1对应/boot /dev/sdb2对应根/mkfs.ext4 /dev/sdb1mkfs.ext4 /dev/sdb2 2、挂载boot mkdir/mnt/bootmount /dev/sdb1 /mnt/boot 3、安装grub grub-i…

    Linux干货 2016-09-16
  • mysql主从复制及zabbix监控从服务器

    Mysql备份: 备份系统的构建,要注意的要点: 第一:能容忍最多丢失多少数据; 第二:恢复数据需要在多长时间内完成; 第三:需要恢复哪些数据:备份时要考虑备份完整; (1)必须做还原测试,用于测试备份的可用性; (2)还原演练;不是一个人能够完成的; 备份类型: 完全备份:就是备份整个数据集,是从时间轴上划分的,完整数据集;; 部分备份:只备份数据子集; …

    Linux干货 2016-12-05
  • Linux发行版的基础目录名称命名法则及功用规定

    [root@localhost /]# tree -L 1. <—-> 为 / 符号,所有文件的根目录;├── bin -> usr/bin <—-> 所有用户可用的基本命令程序文件;├── boot <—-> 引导加载器必须用到的各静态文件:kernel,initramfs(in…

    2018-02-28
  • 系统基础之文件管理工具

    系统基础之文件管理工具   linux的重要哲学思想之一,一切皆文件.那作为系统管理员,就要求对文件的操作管理特别熟悉.那么下面介绍的一个工具可以帮助到大家,更有效,快捷的完成对文件的处理.下面让我们来认识以下的工具. 文本工具: 文件内容:   cat: 复制标准输入到标准输出     选项:   &nbs…

    Linux干货 2016-08-07
  • Linux 第七天: (08月05日) Linux文本处理工具

    Linux 第七天: (08月05日) 文本处理工具       head -n 指定货权前n行tail -n 指定获取后n行tail -f 显示文件新追加内容 tail -n 0 -f /var/log/messages & 后台监控日志 cut -d 指明分隔符,默认tabcut -f 第几个字段cut -c 按字符…

    Linux干货 2016-08-08
  • 马哥教育网络班22期+第4周课程练习

    1、复制/etc/skel目录为/home/tuser1,要求/home/tuser1及其内部文件的属组和其它用户均没有任何访问权限。   cp -r /etc/skel /home/tuser1    chmod -R go=— /home/tuser1 2、编辑/etc/group文件,添加组hadoo…

    Linux干货 2016-09-19