码迷,mamicode.com
首页 > 系统相关 > 详细

shell--if、case语法详解

时间:2016-09-21 23:40:51      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:shell 脚本 if case 语法

1. 条件选择 if 语句

        选择执行:

             单分支

                if 判断条件: then

                  条件为真的分支代码

                fi

                   

             双分支

                if 判断条件; then

                   条件为真的分支代码

                else

                   条件为假的分支代码

                fi

                   

             多分支

                if CONDITION1; then

                    if-true

                elif CONDITION2; then

                    if-ture

                elif CONDITION3; then

                    if-ture

                    …

                else

                    all-false

                fi

   

          逐条件进行判断,第一次遇为“真”条件时,执行其分支,而后结束整个if语句

        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

2.条件判断: case 语句

            case 变量引用 in

                PAT1)

                        分支1

                        ;;

                PAT2)

                        分支2

                        ;;

                        …

                 *)

                        默认分支

                        ;;

            esac


3.练习:

 

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

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

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

read "input your username :" input_user

id $input_user

if [ $? -eq 0 ] ;then

echo" user exist"

else

useradd $input_user

chk_id=`getent passwd $input_user | cut -d: -f 3 `

echo $chk_id

fi

 


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

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

#!/bin/bash

#

read -p "please input yes or no:" input_info

[ -z "$input_info" ] && (echo "error";exit) || uperr_input_info=`echo "$input_info" | tr [a-z] [A-Z]`


case $uperr_input_info in 

Y|YES|NO|N)

echo "right"

;;

*)

echo "other info "

;;

esac



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

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

#!/bin/bash

#

read -p "please input the path :" path_file

if [ -z "$path_file" ];then

echo "you need to input info";exit

else

type_file=`ls -ld $path_file | cut -c1`

echo "the type of the file is : $type_file"

fi



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

是否为正整数

#!/bin/bash

#

read "please input int:" int_put

if [[ "$int_put" =~ ‘^[1-9]+$‘ ]] ;then

echo "it is a int"

elif [ "$int_put" -le 0 ] ;then

ehco "it is fu int or zero"

elif [ "$int_put" -eq 0 ];then 

echo "it is zero"

else

echo "it is not a int"

fi


#也可以使用 expr a + 0 ,即可判断a的类型


shell--if、case语法详解

标签:shell 脚本 if case 语法

原文地址:http://195175108.blog.51cto.com/10167819/1854985

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!