• shell专题(九):函数


    9.1 系统函数

    1.basename基本语法

    basename [string / pathname] [suffix]   (功能描述:basename命令会删掉所有的前缀包括最后一个(‘/’)字符,然后将字符串显示出来。

    选项:

    suffix为后缀,如果suffix被指定了,basename会将pathnamestring中的suffix去掉。

    2.案例实操

    1)截取该/home/atguigu/banzhang.txt路径的文件名称

    [atguigu@hadoop101 datas]$ basename /home/atguigu/banzhang.txt 
    banzhang.txt
    [atguigu@hadoop101 datas]$ basename /home/atguigu/banzhang.txt .txt
    banzhang

    3. dirname基本语法

    dirname 文件绝对路径 (功能描述:从给定的包含绝对路径的文件名中去除文件名(非目录的部分),然后返回剩下的路径(目录的部分))

    4.案例实操

    1)获取banzhang.txt文件的路径

    [atguigu@hadoop101 ~]$ dirname /home/atguigu/banzhang.txt 
    /home/atguigu

    9.2 自定义函数

    1.基本语法

    [ function ] funname[()]

    {

    Action;

    [return int;]

    }

    funname

    2.经验技巧

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

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

    3.案例实操

    1)计算两个输入参数的和

    [atguigu@hadoop101 datas]$ touch fun.sh
    [atguigu@hadoop101 datas]$ vim fun.sh
    
    #!/bin/bash
    function sum()
    {
        s=0
        s=$[ $1 + $2 ]
        echo "$s"
    }
    
    read -p "Please input the number1: " n1;
    read -p "Please input the number2: " n2;
    sum $n1 $n2;
    
    [atguigu@hadoop101 datas]$ chmod 777 fun.sh
    [atguigu@hadoop101 datas]$ ./fun.sh 
    Please input the number1: 2
    Please input the number2: 5
    7
  • 相关阅读:
    MFC tab页面中获到其它页面的数据
    sqlite数据库中"Select * From XXX能查到数据,但是Select DISTINCT group From xxx Order By group却查不出来
    关闭程序出现崩溃(exe 已触发了一个断点及未加载ucrtbased.pdb)
    springboot 通用Mapper使用
    springBoot 发布war包
    springCloud Zuul网关
    springboot hystrix turbine 聚合监控
    springBoot Feign Hystrix Dashboard
    springBoot Ribbon Hystrix Dashboard
    springBoot Feign Hystrix
  • 原文地址:https://www.cnblogs.com/qiu-hua/p/13219694.html
Copyright © 2020-2023  润新知