14

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?

2 Answers 2

22

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

I believe the 2nd example with just a return statement will return the status of the last command prior to calling empty_func. Since this is probably not the intent, it would be safer to use your 1st example, or simply replace return with true.
7

Try this instead:

empty_func() {
  :
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.