在一行中将函数写入 ~/.bashrc

αғs*_*нιη 48 scripts bashrc syntax

为什么当我尝试将一个函数仅在一行中写入.bashrc文件时,

list(){ ls -a }
Run Code Online (Sandbox Code Playgroud)

我得到错误?

bash: /home/username/.bashrc: line num: syntax error: unexpected end of file
Run Code Online (Sandbox Code Playgroud)

但是当我用多行写它时可以吗?

list(){
    ls -a
}
Run Code Online (Sandbox Code Playgroud)

Vol*_*gel 49

;函数末尾需要一个:

list(){ ls -a ; }
Run Code Online (Sandbox Code Playgroud)

应该管用。

bash 函数定义的语法指定为

name () { list ; }
Run Code Online (Sandbox Code Playgroud)

请注意,它包含;不属于list.

;是在这个地方需要的是那种语法异常。它不是bash特定的,对于 来说是一样的ksh,但是;zsh.


mur*_*uru 36

中的函数bash本质上是命名的复合命令(或代码块)。来自man bash

Compound Commands
   A compound command is one of the following:
   ...
   { list; }
          list  is simply executed in the current shell environment.  list
          must be terminated with a newline or semicolon.  This  is  known
          as  a  group  command. 

...
Shell Function Definitions
   A shell function is an object that is called like a simple command  and
   executes  a  compound  command with a new set of positional parameters.
   ... [C]ommand is usually a list of commands between { and },  but
   may  be  any command listed under Compound Commands above.
Run Code Online (Sandbox Code Playgroud)

没有给出任何理由,这只是语法。

由于给出的单行函数中的列表没有以换行符或 a 终止;,因此bash抱怨。


小智 21

换行符暗示单个命令(“;”)的结束。在 oneline 版本中,}被解析为未终止ls -a命令的参数。如果你这样做,你可以看到:

$ foo(){ echo "a" }
}
$ foo
a }
Run Code Online (Sandbox Code Playgroud)

看看函数声明中的命令如何吞下尾随的花括号?

  • 很好的解释!所以它*不*只是一个语法异常;它实际上有一些逻辑。 (2认同)