网站首页 > 基础教程 正文
本系列文章介绍在 Linux Bash shell 中使用函数的一些实例,包括下面的内容:
- 定义函数的格式
- 从函数中返回内容
- 使用函数名作为函数指针
- 函数内执行cd命令的影响
- 声明函数内的变量为局部变量
- 获取传入函数的所有参数
定义函数的格式
在 bash 中,定义函数时,function 关键字是可选的,查看man bash手册,里面提到定义函数的两种格式如下:
name () compound-command [redirection] function name [()] compound-command [redirection]
从中可以看到,当不写 function 关键字时,函数名后面一定要跟着小括号(),而写了 function 关键字时,小括号是可选的。
关于 compound-command 的说明,同样可以查看 man bash 手册,里面提到下面几种形式:
A compound command is one of the following:
(list) list is executed in a subshell environment. Variable assignments and builtin commands that affect the shell's environment do not remain in effect after the command completes. The return status is the exit status of list.
{ list; } list is simply executed in the current shell environment. list must be terminated with a newline or semicolon. The return status is the exit status of list.
常见的是 { list; } 这种形式,但是写为 (list) 也可以。举例如下:
$ testpwd() (pwd) $ testpwd /home/sample/ $ testpwd() ( pwd ) $ testpwd /home/sample/ $ testpwd() (pwd;) $ testpwd /home/sample/
这里定义了一个 testpwd 函数,它自身的代码是用小括号()括起来的 pwd 命令,这个命令跟 () 之间可以有空格,也可以没有空格。在命令后可以加分号,也可以不加分号。
注意:使用 { list; } 这个写法时,在 list 后面一定要跟着分号';',否则会报错。而且 list; 和左边的大括号 { 之间要有空格。如果写为 {list;} 会报错,而 { list;} 不会报错,建议还是写为 { list; } 的形式。举例如下:
$ lsfunc() {ls} -bash: syntax error near unexpected token `{ls}' $ function lsfunc() {ls;} -bash: syntax error near unexpected token `{ls' $ lsfunc() { ls;} $ lsfunc hello.c
调用 bash shell 的函数时,不需要写小括号(),只写函数名即可。
例如执行上面的 lsfunc() 函数,直接写 lsfunc 就可以。如果写成 lsfunc() 反而变成重新定义这个函数。
在函数名后面可以提供要传入的参数列表,不同参数之间用空格隔开。如果某个参数需要带有空格,要用引号把该参数括起来。
PS:未完待续,下篇文章会继续说明,敬请期待~
猜你喜欢
- 2024-10-12 这个为生信学习打造的开源Bash教程真香!!(目录更新)
- 2024-10-12 Shell 函数(杰哥教你Linux) shell中函数
- 2024-10-12 Linux下程序是怎样执行的 linux怎么执行程序
- 2024-10-12 这几个常用 alias,带你高效做事(下)
- 2024-10-12 Shell脚本:函数语法以及实例讲解 shell脚本入门详解
- 2024-10-12 Linux 之 bash 编程 linux bash-4.1
- 2024-10-12 Bash函数:ucase、lcase:借助perl一键转换字符串为大小或小写
- 2024-10-12 Bash Shell制作菜单3部曲:1简单交互菜单|Linux|运维|嵌入式
- 2024-10-12 Bash脚本中的用户交互:暂停、等待按键和倒计时的实现方法
- 2024-10-12 bash问题:是否有函数可以返回字符串的长度?
- 最近发表
- 标签列表
-
- gitpush (61)
- pythonif (68)
- location.href (57)
- tail-f (57)
- pythonifelse (59)
- deletesql (62)
- c++模板 (62)
- css3动画 (57)
- c#event (59)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- exec命令 (59)
- canvasfilltext (58)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- node教程 (59)
- console.table (62)
- c++time_t (58)
- phpcookie (58)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)