• 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位置参数给函数传参。

  • 相关阅读:
    hdu5119 DP
    poj3692 最大点权独立集/最大独立集
    poj2125 最小点权覆盖集
    二分图总结
    poj2531 Network Saboteur
    poj1573 Robot Motion
    poj2632 Crashing Robots
    poj1068
    动态规划的思考(三)
    代刷题目分类(三)
  • 原文地址:https://www.cnblogs.com/renyz/p/11792775.html
Copyright © 2020-2023  润新知