Why cannot I define an empty function in shell?

2019-04-28 21:57发布

I am learning bash. I accidentally encounter a syntax error with empty function.

#!/bin/bash
# script name : empty_function.sh
function empty_func() {
}

bash empty_function.sh

empty_function.sh: line 3: syntax error near unexpected token `}'
empty_function.sh: line 3: `}'

I suppose it is because of definition of an empty function. I would like to know Why I cannot define an empty function?

标签: bash shell
2条回答
叼着烟拽天下
2楼-- · 2019-04-28 22:48

The bash shell's grammar simply doesn't allow empty functions. A function's grammar is:

  name () compound-command [redirection]
  function name [()] compound-command [redirection]

And in a compound command of the form:

{ list; }

list can't be empty. The closest you can get is to use a null statement or return:

function empty_func() {
    : 
}

or

function empty_func() {
    return
}
查看更多
Melony?
3楼-- · 2019-04-28 22:54

Try this instead:

empty_func() {
  :
}
查看更多
登录 后发表回答