Shell脚本通过参数传递调用指定函数


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

Shell编程浅析  

Linux Shell参数替换

Shell for参数

Linux/Unix Shell 参数传递到SQL脚本

Shell脚本中参数传递方法介绍

Shell脚本传递命令行参数

Linux 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"
    ;;

本文永久更新链接地址:

相关内容