shell逻辑控制语句之case

简介:

case分支判断结构 


语法:


case 变量名称 in

value1)

statement

statement

;;

value2)

statement

statement

;;

value3)

statement

statement

;;

       *)

statement

statement

;;

esac



编写脚本,判断用户输入的字符串


#!/bin/bash

#


read -p "Enter string: " str 


case $str in

   linux|Linux)

     echo "windows."

     ;;

   windows|Windows)

     echo "linux."

     ;;

   *)

     echo "other."

     ;;

esac



特殊变量:

位置变量

$1, $2 ,$3 ,$4 ...... $9, ${10}, 


$1: 命令的第1个参数 


$0 命令本身 


$# 命令参数的个数



使用位置变量:


#!/bin/bash

#


case $1 in

  linux)

    echo "windows."

    ;;

  windows)

    echo "linux"

    ;;

  *)

    echo "other"

    ;;

esac




#!/bin/bash

#


if [ -z $1 ]; then

  echo "用法:./11.sh {linux|windows|other}"

  exit 9

fi


case $1 in

  linux)

    echo "windows."

    ;;

  windows)

    echo "linux"

    ;;

  *)

    echo "other"

    ;;

esac



使用$#判断参数是否正确 


#!/bin/bash

#


if [ $# -ne 1 ]; then

  echo "用法:./11.sh {linux|windows|other}"

  exit 9

fi


case $1 in

  linux)

    echo "windows."

    ;;

  windows)

    echo "linux"

    ;;

  *)

    echo "other"

    ;;

esac




[root@shell ~]# basename /etc/sysconfig/network-scripts/ifcfg-eth0  >>>获取文件名称

ifcfg-eth0


[root@shell ~]# dirname /etc/sysconfig/network-scripts/ifcfg-eth0  >>>获取文件所在的目录名称 

/etc/sysconfig/network-scripts

[root@shell ~]# 











本文转自 北冥有大鱼  51CTO博客,原文链接:http://blog.51cto.com/lyw168/1957408,如需转载请自行联系原作者
目录
相关文章
|
Shell
shell脚本里的逻辑思维
shell脚本里的逻辑思维
192 1
|
Shell
shell学习(六) 【case多条件分支语句】
shell学习(六) 【case多条件分支语句】
333 1
|
Shell
Shell脚本中的`case`语句
Shell脚本中的`case`语句
397 5
|
Shell Linux iOS开发
Shell的`case`语句
Shell的`case`语句
199 2
|
Shell
shell编程之条件语句与case语句
shell编程之条件语句与case语句
158 2
|
Shell Linux
linux|shell编程|shell脚本的一些高级技巧(shell脚本内的括号,中括号,花括号,逻辑判断,脚本优雅退出等等)
linux|shell编程|shell脚本的一些高级技巧(shell脚本内的括号,中括号,花括号,逻辑判断,脚本优雅退出等等)
307 0
|
运维 Shell 应用服务中间件
【运维知识高级篇】超详细的Shell编程讲解3(if判断+Shell菜单+case流程判断+批量创建删除用户+猜数字小游戏)
【运维知识高级篇】超详细的Shell编程讲解3(if判断+Shell菜单+case流程判断+批量创建删除用户+猜数字小游戏)
386 1
|
Shell
Shell脚本:case语句
Shell脚本:case语句
169 1
|
Shell
shell之case范例1
shell之case范例1
148 1
|
Java Shell 测试技术
shell编程之条件语句(条件测试、if语句、case语句)(上)
要使Shell脚本程序具备一定的“智能”,面临的第一个问题就是如何区分不同的情况以确定执行何种操作。Shell环境根据命令执行后的返回状态值($?)来判断是否执行成功,当返回值为0时表示成功,否则(非0值)表示失败或异常。 使用专门的测试工具——test命令,可以对特定条件进行测试,并根据返回值来判断条件是否成立(返回值为0表示条件成立)。 使用test测试命令时,有以下两种形式:
433 1