shell编程之函数定义及使用

一.函数定义

#!/bin/sh

#func1.sh

hello()         ##函数定义

{

  echo  "Hello there today's date is 'date +%Y-%m-%d' "

  #return    2       ###返回值其实是状态码,只能在[0-255]范围内

}

echo  "now going to the function hello"

hello

#echo  $?     获取函数的return值

echo  "back from the function"

函数调用:function hello() 或 function hello 或 hello

注意:1.必须在调用函数地方之前,先声明函数,shell脚本是逐行运行,不会像其它语言一样先预                编译

   2.函数返回值,只能通过$?系统变量获得,可以显示加:return返回,如果不加,将以最后                一条命令运行结果,作为返回值。return后跟数值n(0-255)

脚本高度:sh-vx helloWorld.sh或者在脚本中增加set -x

二.函数参数

#!/bin/bash

#fun1.sh

funWithParam(){

  echo "第一个参数为  $1!"

  echo "第二个参数为  $2!"

  echo "第十个参数为  $10!"

  echo "第十个参数为  ${10}!"

  echo "第十一个参数为  ${11}!"

  echo "参数总数有 $# 个!"

  echo "作为一个字符串输出所有参数  $* !"

}

funWithParam 1 2 3 4 5 6 7 8 9 34 73

注意:$10不能获取第十个参数,获取第十个参数需要${10},当n>=10 时,需要使用${n}来获取参数。

三.跨脚本调用函数

假如上述的脚本文件fun1.sh保存在此路径:  /root/fun1.sh,则可在脚本fun_other.sh中调用脚本fun1.sh中的函数

#!/bin.bash

#fun_other.sh

. /root.fun1.sh   ##注: . 和/之间有空格

# 或者source /root/fun1.sh

funWithParam 11 22 33 44 55 66 77 88 99 100 101

猜你喜欢

转载自www.cnblogs.com/chengting/p/11538107.html