9.1 系统函数

9.1.1 basename

1)基本语法 :::info basename [string / pathname] [suffix] ( 功能描述: basename 命令会删掉所有的前缀包括最后一个(‘/’) 字符, 然后将字符串显示出来。
basename 可以理解为取路径里的文件名称
选项:
suffix 为后缀, 如果 suffix 被指定了, basename 会将 pathname 或 string 中的 suffix 去掉。 ::: 2)案例实操
截取该 /home/xiaoming/helloworld.sh 路径的文件名称

  1. ~ basename /home/xiaoming/helloworld.sh
  2. helloworld.sh
  3. ~ basename /home/xiaoming/helloworld.sh .sh
  4. helloworld

9.1.2 dirname

1)基本语法 :::info dirname 文件绝对路径 (功能描述: 从给定的包含绝对路径的文件名中去除文件名(非目录的部分) , 然后返回剩下的路径(目录的部分) )
dirname 可以理解为取文件路径的绝对路径名称 ::: 2)案例实操
截取该 /home/xiaoming/helloworld.sh 路径

  1. ~ dirname /home/xiaoming/helloworld.sh
  2. /home/xiaoming

9.2 自定义函数

1)基本语法 :::info [ function ] funname[()]
{
Action;
[return int;]
}
funname ::: 2)经验技巧
(1) 必须在调用函数地方之前, 先声明函数, shell 脚本是逐行运行。 不会像其它语言一样先编译。
(2) 函数返回值, 只能通过$?系统变量获得, 可以显示加: return 返回, 如果不加, 将以最后一条命令运行结果, 作为返回值。 return 后跟数值 n(0-255)
3)案例实操
计算两个输入参数的和。

  1. ~ touch function.sh
  2. ~ vim function.sh
  3. #!/bin/bash
  4. function sum()
  5. {
  6. sum=0
  7. sum=$[ $1+$2 ]
  8. echo "$sum";
  9. }
  10. read -p "Please input the number1:" n1
  11. read -p "Please input the number2:" n2
  12. sum $n1 $n2;
  13. ~ chmod 777 function.sh
  14. ~ bash function.sh
  15. Please input the number1:1
  16. Please input the number2:2
  17. 3
  1. cat function_test.sh
  2. #!/bin/bash
  3. function add() {
  4. sum=$[ ${1} + ${2} ]
  5. echo $sum
  6. }
  7. read -p "请输入第一个整数:" number1
  8. read -p "请输入第二个整数:" number2
  9. sum=$(add $number1 $number2)
  10. echo "总和:" $sum
  11. echo "总和的平方:"$[ $sum*$sum ]