1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 10 i lt shell的if_shell脚本编程之if case条件语句

10 i lt shell的if_shell脚本编程之if case条件语句

时间:2019-03-25 03:31:38

相关推荐

10 i lt shell的if_shell脚本编程之if case条件语句

程序执行三种顺序

顺序执行

选择执行

循环执行

选择执行语句:

if语句

格式:

单分支:

if 判断条件;then

条件分支代码

fi

双分支:

if 判断条件;then

条件为真时语句

else (此处不会对给出的条件做判断)

条件为假时语句

fi

多分支:

if 条件1;then

代码

elif 条件2;then

代码

elid 条件2;then

代码

else

代码

fi

例子:输入两个数,判断其大小

[root@centos7bin]#catf1

#!/bin/bash

read-p"inputanumber:"m

read-p"inputanumber:"n

if[$m-gt$n];then

echo"$m>$n"

else[$m=$n]此程序中,else后面的判断无效,如果m=n或者m

echo"$m=$n"

fi

[root@centos7bin]#

[root@centos7bin]#

if语句例子

if ping – c1 – W2 station1 &> /dev/null; then

echo 'Station1 is UP'

elif grep "station1" ~/maintenance.txt &> /dev/null

then

echo 'Station1 is undergoing maintenance‘

else

echo 'Station1 is unexpectedly DOWN!'

exit 1

fi

条件判断case

case 变量 in

pat1)

分支1

;;

part2)

分支2

;;

part3)

分支3

;;

esac

注意:case 支持glob的通配符

循环语句综合练习:

1、写一个脚本/root/bin/createuser.sh,实现如下功能:使用一个用户名做为参数,如果指定参数的用户存在,就显

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

2、写一个脚本/root/bin/yesorno.sh,提示用户输入yes或no,并判断用户输入的是yes还是no,或是其它信息

3、写一个脚本/root/bin/filetype.sh,判断用户输入文件路径,显示其文件类型(普通,目录,链接,其它文件类型)

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

答案:1

[root@centos7bin]#catuseradd.sh

#!/bin/bash

read-p"pleaseinputtheusername:"username

ifid-u$username&>/dev/null;then

echo"theuser$usernameexit"

else

useradd$username

echo"useraddsuccess,userIDis`id-u$username`"

fi

[root@centos7bin]#

答案:2

[root@centos7bin]#catcaseyesorno.sh

#!/bin/bash

read-p"pleaseinputyesorno:"yn

case$ynin

yes|y|0|Y|[yY][Ee][Ss])

echo"youinputis:$yn"

;;

no|[Nn][Oo]|N|n)

echo"youinputis:$yn"

;;

*)

echo"youinputisother"

esac

[root@centos7bin]#

[root@centos7bin]#catyesorno.sh

#!/bin/bash

read-p"pleaseinputyesorno:"yn

if[[$yn=~[yY][eE][sS]||[Yy]]];then

echo"youinputis:yes"

elif[[$yn=~[nN][oO]||[Nn]]];then

echo"youinputis:no"

else

echo"youinputisother"

fi

[root@centos7bin]#

答案:3

[root@centos7bin]#catfiletype.sh

#!/bin/bash

read-p"pleaseinputfilename:"filename

[!-e$filename]&&echo"filenamenotexit"&&exit

if[-h$filename];then注意:软链接文件也被识别为普通文件,正确判断出软链接文件,将-h条件放到-f文件前去判断

echo"filetypeissymolinkfile"

elif[-d$filename];then

echo"filetypeisdirction"

elif[-f$filename];then

echo"filetypeiscommonfile"

else

echo"filetypeisother"

fi

[root@centos7bin]#

答案:4

[root@centos7bin]#catcheckint.sh

#!/bin/bash

read-p"pleaseinputanum:"num

if[$num-lt1];then

echo"pleaseinputainit"

elif[[$num=~^[[:digit:]]+$]];then

echo"youinputisaint"

else

echo"inputerror"

fi

[root@centos7bin]#

原创文章,作者:wangnannan,如若转载,请注明出处:/35866

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。