zoukankan      html  css  js  c++  java
  • shell基础之函数

      shell中允许将一组命令集合或语句形成一段可用代码,这些代码块称为shell函数。给这段代码起个名字称为函数名,后续可以直接调用该段代码。

      格式:

    func() {   #指定函数名
    command    #函数体
    }

      实例1:

    [root@ren01 ~]# cat test1.sh 
    #!/bin/bash
    func() {
    echo "this is a function."
    }
    func
    [root@ren01 ~]# sh test1.sh 
    this is a function.

      Shell 函数很简单,函数名后跟双括号,再跟双大括号。通过函数名直接调用,不加小括号。

      实例2:函数返回值

    [root@ren01 ~]# cat test2.sh 
    #!/bin/bash
    func() {
    VAR=$((1+6))
    return $VAR
    echo "this is a function2."
    }
    func
    echo $?
    [root@ren01 ~]# sh test2.sh 
    7

      return 在函数中定义状态返回值,返回并终止函数,但返回的只能是 0-255 的数字,类似于 exit。

      实例3:函数传参

    [root@ren01 ~]# cat test3.sh 
    #!/bin/bash
    func() {
    echo "hello $1"
    }
    func world
    [root@ren01 ~]# sh test3.sh 
    hello world

      通过shell位置参数给函数传参。

  • 相关阅读:
    jQuery应用 代码片段
    正则表达式大全
    js表单编程
    补充回顾
    Socket网路编程
    异常处理
    day18-2 反射详解
    day18-1 面向对象进阶
    day18-1 多态
    day17-2 继承
  • 原文地址:https://www.cnblogs.com/renyz/p/11792775.html
Copyright © 2011-2022 走看看