Appearance
八、函数
1、系统函数
1、basename
1、基本语法
basename [string / pathname] [suffix] (功能描述:basename 命令会删掉所有的前缀包括最后一个(‘/’)字符,然后将字符串显示出来。
basename 可以理解为取路径里的文件名称 选项: suffix 为后缀,如果 suffix 被指定了,basename 会将 pathname 或 string 中的 suffix 去掉。
2、案例实操
截取该/home/xue/banzhang.txt 路径的文件名称。
sh
[root@k8s-node shells]$ basename /home/xue/banzhang.txt
banzhang.txt
[root@k8s-node shells]$ basename /home/xue/banzhang.txt .txt
banzhang
2、dirname
1、基本语法
dirname 文件绝对路径 (功能描述:从给定的包含绝对路径的文件名中去除文件名(非目录的部分),然后返回剩下的路径(目录的部分))
dirname 可以理解为取文件路径的绝对路径名称
2、案例实操
获取 banzhang.txt 文件的路径。
sh
[root@k8s-node ~]$ dirname /home/xue/banzhang.txt
/home/xue
2、自定义函数
1、基本语法
sh
[ function ] funname[()]
{
Action;
[return int;]
}
2、经验技巧
- 必须在调用函数地方之前,先声明函数,shell 脚本是逐行运行。不会像其它语言一样先编译。
- 函数返回值,只能通过$?系统变量获得,可以显示加:return 返回,如果不加,将以最后一条命令运行结果,作为返回值。return 后跟数值 n(0-255)
3、案例实操
计算两个输入参数的和。
sh
[root@k8s-node shells]$ touch fun.sh
[root@k8s-node shells]$ 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;
[root@k8s-node shells]$ chmod 777 fun.sh
[root@k8s-node shells]$ ./fun.sh
Please input the number1: 2
Please input the number2: 5
7