1. 系统函数

1.1 basename

基本语法:basename [ string / pathname ] [ suffix ]
功能描述:basename 命令会删除所有的前缀包括最后一个(‘/’)字符,然后将字符串显示出来
选项:suffix 为后缀,如果 suffix 被指定了,basename 会将 string 或 pathname 中的 suffix 去掉

1.2 案例实操

  1. [root@localhost ~]# basename /root/test.txt
  2. test.txt
  3. [root@localhost ~]# basename /root/test.txt .txt
  4. test

1.3 dirname

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

1.4 案例实操

(1 )获取第3章节已经创建的test.txt的路径

  1. [root@localhost ~]# dirname /root/test.txt
  2. /root

2. 自定义函数

2.1 基本语法

  1. [ function ] funname[()]
  2. {
  3. Action;
  4. [return int;]
  5. }

2.2 案例实操

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

  1. [root@localhost ~]# touch fun.sh
  2. [root@localhost ~]# chmod 777 fun.sh
  3. [root@localhost ~]# vim fun.sh
  4. #!/bin/bash
  5. function sum()
  6. {
  7. s=0
  8. s=$[ $1 + $2 ]
  9. echo "$s"
  10. }
  11. read -p "Please enter the number 1: " n1;
  12. read -p "Please enter the number 2: " n2;
  13. sum $n1 $n2;
  14. [root@localhost ~]# ./fun.sh
  15. Please enter the number 1: 10
  16. Please enter the number 2: 20
  17. 30

2.3 经验技巧

(1)必须在调用函数地方之前,先声明函数,shell脚本是逐行运行。不会像其它语言一样先编译。
(2)函数返回值,只能通过$?系统变量获得,可以显示加:return返回,如果不加,将以最后一条命令运行结果,作为返回值。return后跟数值n(0-255)