shell编程 | case语句、shell脚本函数

case … esac 与其他语言中的 switch … case 语句类似,是一种多分枝选择结构。

casein
模式1)
    command1
    command2
    command3
    ;;
模式2)
    command1
    command2
    command3
    ;;
*)
    command1
    command2
    command3
    ;;
esac

示例:

#!/bin/bash

echo "input:"
read line

# 初探case 语句
case "$line" in
	yes | Yes | y) echo -e "\n--- Yes" ;;  
	no  | No  | n) echo -e "\n--- No" ;;
	*) echo -e  "\ninput="$line ;;
esac

exit 0

在这里插入图片描述
在这里插入图片描述

使用正则表达式

# 用正则表达式进行匹配
case "$line" in
	[Yy][Ee][Ss] | [Yy]) echo "this is Yes" ;;
	[Nn][Oo] | [Nn]) echo "this is No" ;;
	*) ;;
esac

函数

# 函数
# 没有申明,需要写在执行之前,无返回值类型和参数列表
# 有返回值,可以传参 
# 程序以第一行非函数语句执行
fun()
{
	echo "fun run"
	echo "fun \$#=$#"	#参数个数
	echo "fun \$1=$1"
	echo "fun \$2=$2"
	echo "fun \${10}=${10}"
}

# 函数名调用函数
fun 123 hello 1 2 3 4 5 6 7 8 9

在这里插入图片描述

函数返回值

#!/bin/bash

# 函数的返回值
my_add()
{
	if [ "$#" -ne 2 ]		#参数的个数
	then
		echo "arg error"
		return -1
	fi

	a=$1
	b=$2

	res=`expr $a + $b`
	return "$res"
}

my_add $1 $2
echo $?		# $? 紧跟着的函数(或语句)的返回值


exit 0

在这里插入图片描述


局部变量

#!/bin/bash

# shell脚本不区分临时变量与全局变量
# 不论变量定义在函数内还是函数外,都是定义在解释器中
# 如果不想临时变量占用资源,可以使用 unset var 命令撤销一个已定义的变量
#							或者使用 local 定义变量,在变量离开时会自动撤销
# 因此shell脚本不强调返回值,返回值可以由一个变量保存带出


myfun()
{
	local	str="hello"
	str2="world"
	str3="test"

	unset str2
}

myfun
echo "str=$str"
echo "str2=$str2"
echo "str3=$str3"


exit 0

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我叫RT

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值