笔记簿
ᴄᴏᴅɪɴɢ ɪs ᴀʀᴛ
首页
关于
搜索
登录
注册
Shell 函数 - shell中的系统函数和自定义函数
#### 系统函数 ##### 1.basename基本语法 ```text basename [string / pathname] [suffix] (功能描述:basename命令会删掉所有的前缀包括最后一个(‘/’)字符,然后将字符串显示出来。 选项: suffix为后缀,如果suffix被指定了,basename会将pathname或string中的suffix去掉。 ``` - 案例 ```text 截取该/home/lynn/Downloads/bafor.sh路径的文件名称 lynn@promptness Downloads % basename /Users/lynn/Downloads/for.sh for.sh lynn@promptness Downloads % basename /Users/lynn/Downloads/for.sh .sh for ``` ##### 2.dirname基本语法 ```text dirname 文件绝对路径 (功能描述:从给定的包含绝对路径的文件名中去除文件名(非目录的部分),然后返回剩下的路径(目录的部分)) ``` - 案例 ```text lynn@promptness Downloads % dirname /Users/lynn/Downloads/for.sh /Users/lynn/Downloads ``` #### 自定义函数 ##### 1.基本语法 ```text [ function ] funname[()] { Action; [return int;] } ```
注意:
(1)必须在调用函数地方之前,先声明函数,shell脚本是逐行运行。不会像其它语言一样先编译。
(2)函数返回值,只能通过$?系统变量获得,可以显示加:return返回,如果不加,将以最后一条命令运行结果,作为返回值。return后跟数值n(0-255)
##### 3.案例 ```text 计算两个输入参数的和 #!/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; ```