扣丁书屋

在函数中使用参数

1年以前  |  阅读数:122 次  |    

#!/bin/bash

# passing parameters to a function

function addem {
    if [ $# -eq 0 ] || [ $# -gt 2 ]
    then 
        echo -1
    elif [ $# -eq 1 ]
    then 
        echo $[ $1 + $1 ]
    else
        echo $[ $1 + $2 ]
    fi
}

echo -n "Adding 10 and 15:"
value=`addem 10 15`
echo $value

echo -n "Let's try adding just one number: "
value=`addem 10`
echo $value

echo -n "Now trying adding no number: "
value=`addem`
echo $value

echo -n "Finally, try adding three or more numbers: "
value=`addem 10 15 20`
echo $value

相关文章: