Why when I try to write a function just in one line into .bashrc file,

list(){ ls -a }

I get error?

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

but when I write it in multi line it's ok?

    ls -a

Functions in bash are essentially named compound commands (or code blocks). From 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.

There's no reason given, it's just the syntax.

Since the list in the one-line function given isn't terminated with a newline or a ;, bash complains.

| improve this answer | |

There is a ; needed at the end of the function:

list(){ ls -a ; }

should work.

The syntax of a function definition for bash is specified as

name () { list ; }

Note that it includes a ; that is not part of the list.

That the ; is required in this place is kind of a syntax anomaly. It is not bash specific, it's the same for ksh, but it the ; is not required in zsh.

| improve this answer | |

The end of a single command (";") is implied by the newline. In the oneline version } is parsed as an argument to the unterminated ls -a command. Which you can see if you do:

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

See how the command inside the function declaration swallows the trailing curly brace?

| improve this answer | |
  • 2
    Great explanation! So it's not just a syntax anomaly; there's actually some logic to it. – Don Hatch Jan 13 '16 at 12:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.