Understanding semicolons in Bash functions
I know I can write a function at a Bash command line like so:
$ test() { echo 'test' ; }
I also found that I can write the }
on a separate line, and omit ;
:
$ test () { echo 'test'
> }
But I cannot omit ;
when inputting on the same line:
$ test () { echo 'test' }
>
>
Here, the interface for inputting a multi-line function doesn't exit until I either cancel it manually, input a ;
(resulting in an immediate syntax error), or input a }
(resulting in an extra }
in the function (now the }
becomes an argument to echo
instead).
On the other hand, if I want the process to be backgrounded, I need not and indeed cannot use ;
:
$ test () { echo 'test' & }
creates the function immediately which works as expected, but
$ test () { echo 'test' & ;
is an immediate syntax error (giving no chance to input the balancing }
), and is still a syntax error with a }
on the same line. I tried swapping the &
and ;
but with no meaningful effect.
What does ;
actually do in a Bash function?
Consequently: Why isn't }
on the same line recognized as a closing brace for the function without either ;
or &
at the end of the command? Why is it recognized as such on a separate line? Why do I need ;
for an ordinary command invocation, but not for a backgrounded one?
1 answer
The shell uses ;
to reliably end a statement. In some cases, a line break also ends a statement (except that when the statement is obviously incomplete, a line break does not end it). (I don't know if "statement" is the technical term.)
I personally always use ;
as if I were writing C code, unless running some one-liner interactively. IMO, the semicolons add readability.
0 comment threads