Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4213518
  • 博文数量: 1148
  • 博客积分: 25453
  • 博客等级: 上将
  • 技术积分: 11949
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-06 21:14
文章分类

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: Python/Ruby

2011-01-19 11:04:57

函数这样定义?
       要定义一个函数,你只需写出他的名字,然后是一个空括号
  1. funciton_name () {
  2.     statement
  3. }
一个很简单的函数事列
  1. #!/bin/sh
  2. foo() {
  3.     echo "funciton foo is executing"
  4. }

  5. echo "sricpt starting"
  6. foo
  7. echo "script ended"

  8. exit 0


当一个函数被调用时,脚本程序的位置参数($* $@ $1 $2等)会被替换为函数的参数,这也是你读取传递给函数的参数的方法
当调用完后,这些参数会恢复为它们先前的值。

从函数中返回一个值

脚本程序my_name演示了函数的参数是如何传递的,以及函数如何返回一个true或false的。

  1. #!/bin/sh

  2. #首先定义了函数

  3. yes_or_no() {
  4.     echo "is it your name $1"
  5.     while true
  6.     do
  7.           echo -n "enter yes or no: "
  8.      read x
  9.      case "$x" in
  10.         y|yes|Y|YES) return 0;;
  11.                 n|N ) return 1;;
  12.                 * ) echo "answer yes or no"
  13.      esac
  14.        done    
  15. }
#住程序部分
  1. echo "orginal paramters are $*"
  2.                     #函数传值
  3. if yes_or_no "$1"   #传入第一个参数
  4. then
  5.     echo "hi $1,nice name"
  6. else
  7.     echo "never remember"
  8. fi
  9. exit 0




函数调用:两种方式

1. 在一个脚本中调用函数
  1. #!/bin/bash
  2. # third.sh

  3. hello ()
  4. {
  5.         echo "hello"
  6. }

  7. hello


2. 在其他脚本中调用
first.sh
  1. #!/bin/bash

  2. # first.sh

  3. hello ()
  4. {
  5.         echo " helllo"
  6. }
second.sh
  1. #!/bin/bash
  2. # second.sh

  3. . /home/ywx/desktop/linux_shell/first.sh
  4.        #调用first.sh脚本中的函数
  5. hello













阅读(786) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~