Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Post History

66%
+2 −0
Q&A 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' > } ...

1 answer  ·  posted 3d ago by Karl Knechtel‭  ·  last activity 1d ago by alx‭

#1: Initial revision by user avatar Karl Knechtel‭ · 2025-01-19T07:02:13Z (3 days ago)
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?