linux+带参数函数调用,Shell脚本通过参数传递调用指定函数

我们在写一些功能性Shell脚本的时候,往往会把操作相似或者参数类似行为接近的函数放在同一个shell脚本中,这样管理方便,维护简单,也很清晰。对于这种情况,通常的办法是,在shell脚本中定义所有用到的函数,然后在正文代码中用case语句读入输入的命令函数参数来调用指定的相应函数。这样就达到一个shell脚本使用的强大功能。

下面以一个简单的例子来说明。一个计算器提供了加减乘除的功能:

#!/bin/bash

usage="Usage: `basename $0` (add|sub|mul|div|all) parameter1 parameter2"

command=$1

first=$2

second=$3

function add() {

ans=$(($first + $second))

echo $ans

}

function sub() {

ans=$(($first - $second))

echo $ans

}

function mul() {

ans=$(($first * $second))

echo $ans

}

function div() {

ans=$(($first / $second))

echo $ans

}

case $command in

(add)

add

;;

(sub)

sub

;;

(mul)

mul

;;

(div)

div

;;

(all)

add

sub

mul

div

;;

(*)

echo "Error command"

echo "$usage"

;;

esac

上面的这段shell脚本,我们就可以通过传入不同的参数调用达到不同的目的。

[hdfs@cdhonf]$ ./calculator add 2 3

5

[hdfs@cdhonf]$ ./calculator sub 2 3

-1

[hdfs@cdhonf]$ ./calculator mul 2 3

6

[hdfs@cdhonf]$ ./calculator div 2 3

0

[hdfs@cdhonf]$ ./calculator all 2 3

5

-1

6

0

[hdfs@cdhonf]$ ./calculator a 2 3

Error command

Usage: calculator (add|sub|mul|div|all) parameter1 parameter2

倘若我们不想每个函数都用同样个数的参数,也就是不同的函数参数不一样时候怎么办?这时候我们可以在函数体的内部读入参数,然后在case后的相应调用语句时候也传入相应的参数。

function double() {

ans=$(($1 + $1))

echo $ans

}

case $command in

(dou)

double "$first"  #you can also use "$2"

;;

0b1331709591d260c1c78e86d0c51c18.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值