shell 函数定义 和 使用

来源:互联网 发布:厦门金猪网络 编辑:程序博客网 时间:2024/04/26 22:55

#!/bin/bash

function test()
{
echo $#
for param in $*
do
echo "param " $param
done

return 9;
}


echo "before call test"
test "ab" "cd" "ef"
result=$? # 这里的返回值不能超过 255
echo "after call test"

echo $result

========================================

$0:是脚本本身的名字;
$#:是传给脚本的参数个数;
$@:是传给脚本的所有参数的列表,即被扩展为"$1" "$2" "$3"等;
$*:是以一个单字符串显示所有向脚本传递的参数,与位置变量不同,参数可超过9个,即被扩展成"$1c$2c$3",其中c是IFS的第一个字符;
$$:是脚本运行的当前进程ID号;
$?:是显示最后命令的退出状态,0表示没有错误,其他表示有错误;

========================================

如果函数想返回字符串

function fun()

{

echo "abc"

}

result=$(fun)   # 这里讲返回的字符串保存到变量里

========================================

#!/bin/bash


function little_addfunc()
{
   # 这里不能让两个数的和大于255,要不 $? 该反转保存了
echo "addfunc in"
echo $1
echo $2
return $(($1+$2))
}


function stringCombin()
{
echo "$1$2"
}


function big_addfunc()
{
#这里没有什么关系,按照正常的加法进行,没有使用return语句
echo `expr $1 + $2`
}


echo "test begin"
echo "== little_addfunc =="
little_addfunc 100 155  # 预期传入的数字是 100 和 155
total=$?
echo "total = $total"
echo "== stringCombin =="
result=$(stringCombin "ab" "cd")
echo "result = $result"
echo "== big_addfunc =="
res=$(big_addfunc 100 200) # 将结果保存成了数字
echo "res = $res"
echo `expr $res + 100`




原创粉丝点击