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 路径的文件名称
➜ ~ basename /home/xiaoming/helloworld.sh
helloworld.sh
➜ ~ basename /home/xiaoming/helloworld.sh .sh
helloworld
9.1.2 dirname
1)基本语法
:::info
dirname 文件绝对路径 (功能描述: 从给定的包含绝对路径的文件名中去除文件名(非目录的部分) , 然后返回剩下的路径(目录的部分) )
dirname 可以理解为取文件路径的绝对路径名称
:::
2)案例实操
截取该 /home/xiaoming/helloworld.sh 路径
➜ ~ dirname /home/xiaoming/helloworld.sh
/home/xiaoming
9.2 自定义函数
1)基本语法
:::info
[ function ] funname[()]
{
Action;
[return int;]
}
funname
:::
2)经验技巧
(1) 必须在调用函数地方之前, 先声明函数, shell 脚本是逐行运行。 不会像其它语言一样先编译。
(2) 函数返回值, 只能通过$?系统变量获得, 可以显示加: return 返回, 如果不加, 将以最后一条命令运行结果, 作为返回值。 return 后跟数值 n(0-255)
3)案例实操
计算两个输入参数的和。
➜ ~ touch function.sh
➜ ~ vim function.sh
#!/bin/bash
function sum()
{
sum=0
sum=$[ $1+$2 ]
echo "$sum";
}
read -p "Please input the number1:" n1
read -p "Please input the number2:" n2
sum $n1 $n2;
➜ ~ chmod 777 function.sh
➜ ~ bash function.sh
Please input the number1:1
Please input the number2:2
3
cat function_test.sh
#!/bin/bash
function add() {
sum=$[ ${1} + ${2} ]
echo $sum
}
read -p "请输入第一个整数:" number1
read -p "请输入第二个整数:" number2
sum=$(add $number1 $number2)
echo "总和:" $sum
echo "总和的平方:"$[ $sum*$sum ]