shell--ifcase语法详解

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了shell--ifcase语法详解相关的知识,希望对你有一定的参考价值。

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--ifcase语法详解的主要内容,如果未能解决你的问题,请参考以下文章

dockerfile详解文件指令详解

Go语言 语法详解笔记(上)

Markdown常用语法详解

Markdown常用语法详解

Markdown常用语法详解

Java 语法糖详解