专业编程基础技术教程

网站首页 > 基础教程 正文

Bash函数用法(1):详解定义函数的两种格式

ccvgpt 2024-10-12 14:06:49 基础教程 10 ℃


本系列文章介绍在 Linux Bash shell 中使用函数的一些实例,包括下面的内容:

Bash函数用法(1):详解定义函数的两种格式

  • 定义函数的格式
  • 从函数中返回内容
  • 使用函数名作为函数指针
  • 函数内执行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:未完待续,下篇文章会继续说明,敬请期待~

Tags:

最近发表
标签列表