一、case语句语法结构
1.工作原理
- case语句为多重匹配语句 ●
- 如果匹配成功,执行相匹配的命令
2.语法结构
case var in pattern 1) command 1 pattern 2) command 2 *) command 3 ;; esac
3. 应用案例
判断用户输入的字符串,如果是"hello",则显示"world";如果是"world", 则显示"hello",否则提示"请输入hello或者world,谢谢!"
#!/bin/bash read -p "keyin: " name case $name in hello) echo world ;; world) echo hello ;; *) echo "keyin hello or world" echo "请输入hello或者world,谢谢!" ;; esac
二、函数
1.什么是函数?
- shell中允许将一组命令集合或语句形成一段可用代码,称为shell函数
- 给这段代码起个名字称为函数名,后续可以直接调用该段代码的功能
2.函数定义
方法一: 函数名() { 函数体(一堆命令的集合,来实现某个功能) } 方法二: function 函数名() { 函数体(一堆命令的集合,来实现某个功能) echo hello echo world }
3.有颜色的字符串输出
#!/bin/bash red="\033[31m" green="\033[32m" yellow="\033[33m" end="\033[0m" print_color_string(){ color=$1 string=$2 case $color in red) echo -e "$red $string $end" ;; green) echo -e "$green $string $end" ;; yellow) echo -e "$yellow $string $end" ;; *) echo $string ;; esac } print_color_string 'red' 'hello shell' print_color_string 'green' 'hello shell' print_color_string 'yellow' 'hello shell'