曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 7595|回复: 0
打印 上一主题 下一主题

shell 函数的应用

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34387
跳转到指定楼层
楼主
发表于 2009-1-12 13:12:11 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
一、函数的定义

函数可以放在同一个文件中作为一段代码,也可以放在只包含函数的单独文件中
#!/bin/bash
#hello-fun
function hello()
{
echo "hello,today is `date`"
return 1
}

二、函数的调用
#!/bin/bash
#func
function hello()
{
         echo "hello,today is `date`"
}

echo "now going to the function helo()"
hello        #直接写函数文件名进行函数调用
echo "back from the hell()"

三、参数的传递
#!/bin/bash
#func
function hello()
{
         echo "hello $1"
}

echo "now going to the function helo()"
hello argument-1              # argument-1 是 $1
echo "back from the hello()"

四、从另外的文件中调用函数

主脚本文件
#!/bin/bash
#func
#source function
. hellofun       # hellofun 文件里有需要调用的函数
echo "now going to the function hello"
hello
echo "back from the function"

函数文件
#!/bin/bash
#hellofun
functon hello()
{
    echo
"
hello, today is `date`
    return 1
}

查看载入函数set
删除函数    : unset

五、函数的返回值

函数文件
#!/bin/bash
#hellofunctions

function hello()
{
    echo "hello,today is `date`"
    return 0
}

shell 程序文件
#!/bin/bash
#func
. hellofunctions    # include 函数文件
echo "now going to the function hello"
hello
echo $?      # 特殊变量 $? 得到返回值
echo "back from the function"

注: shell 函数不像其他语言的函数,可以带回返回值然后赋给变量(通过 $? 变量),比如:
[Bash shell] 纯文本查看 复制代码
#!/bin/sh
 
 function myfunc() {
         echo "return a value"
         return 2
 }
 myfunc
 ret=$?
 
 echo $ret

运行输出:
[beyes@beyes   command]$ sh tmp.sh
return a value
2
注意,获取返回值,不能直接将函数赋值给变量,如上面的不能写成 ret=`myfunc` ,然后觉得 $ret 的值为 2 ,而是需要用 $? 变量进行赋值。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2024-6-17 02:08 , Processed in 0.066784 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表