将函数一行写入〜/ .bashrc


40

为什么当我尝试只在一行中写入一个函数时.bashrc

list(){ ls -a }

我出错了吗?

bash: /home/kasiya/.bashrc: line num: syntax error: unexpected end of file

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

list(){
    ls -a
}

稍后,在Stack Overflow上有一个等效的问题。
sampablokuper

Answers:


33

中的函数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.

没有给出任何原因,只是语法。

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


42

;函数结尾处有一个需要:

list(){ ls -a ; }

应该管用。

bash函数定义的语法指定为

name () { list ; }

请注意,它包含;,而不是的一部分list

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


18

换行符表示单个命令(“;”)的结尾。在单行版本}中,将其作为未终止ls -a命令的参数进行解析。您可以查看是否这样做:

$ foo(){ echo "a" }
}
$ foo
a }

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


2
很好的解释!因此,它只是一个语法异常; 实际上有一些逻辑。
唐·哈奇
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.