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

Understanding semicolons in Bash functions

+2
−0

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?

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.
Why should this post be closed?

0 comment threads

1 answer

+0
−0

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.

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.

0 comment threads

Sign up to answer this question »